The association is in a relationship between two classes.In this type of relationship, both classes know about the connection.
Following Example :
- Make three-class Person, Woman , Man
- A person has a class inheritance in Woman and man class
- Man and Woman class has friend function marry to show they are married
- Man and woman can do more than one marriage so its multiplicities example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include<iostream> | |
using namespace std; | |
class Person | |
{ | |
protected: | |
string name; | |
public: | |
Person(string n) | |
{ | |
name=n; | |
} | |
}; | |
class Man; | |
class Woman:public Person | |
{ | |
private: | |
Man *husband;//Object of Man class inside Woman | |
public: | |
Woman(string n):Person{n},husband{nullptr}{} | |
friend void marry(Man &m,Woman &w);// Friend function can use both Man and woman class connect as friend | |
friend ostream& operator <<(ostream & out,Woman &w);//operator overloading | |
}; | |
class Man:public Person | |
{ | |
private: | |
Woman *wife;//Woman class obj inside man class | |
public: | |
Man(string n):Person{n},wife{nullptr}{} | |
public: | |
friend void marry(Man &m,Woman &w); | |
friend ostream& operator <<(ostream & out,Man &m); | |
friend ostream& operator <<(ostream & out,Woman &w); | |
}; | |
ostream & operator<<(ostream & out,Man &m) | |
{ | |
out<<m.name<<endl; | |
return out; | |
} | |
ostream & operator<<(ostream & out,Woman &w) | |
{ | |
out<<w.name<<endl; | |
return out; | |
} | |
void marry(Man &m,Woman &w) | |
{ | |
m.wife=&w; | |
w.husband=&m; | |
cout<<m<<" marry to "<<w <<endl; | |
} | |
int main() | |
{ | |
Man hus("Raj"); | |
Woman wif("Pooja"); | |
marry(hus,wif); | |
cout<<"Pooja and raj are not married not now "<<endl; | |
Man hus2("Sammer"); | |
marry(hus2,wif); | |
return 0; | |
} |
Raj marry to Pooja Pooja and raj are not married not now Sammer marry to Pooja
0 Comments
If you have any doubt and suggestion Please let me know