Containership or Composition: (Classes within classes) When you define a class object within another class, it is called composition. In the below example class B contains the object of class A. This is called “has-a” relationship. This is contrary to inheritance which is called “kind-of” relationship.
#include <iostream>
using namespace std;
class A
{
public:
int ai;
A():ai(10){}
};
class B
{
public:
int bi;
A a; /* Embedded object */
B():bi(20){}
};
class AA
{
public:
int aai;
class BB /* Here the entire class itself is declared with the another class */
{
public:
int bbi;
BB():bbi(50){}
}temp; /* temp object is created for class BB within class AA. Hence "temp" is an embedded object. For every object you create for class AA, temp will be a data member of that object */
AA():aai(100){}
};
int main()
{
B b;
cout<<"B.A.i "<<b.a.ai<<endl;
cout<<"B.i "<<b.bi<<endl;
AA aa;
cout<<"AA.aai "<<aa.aai<<endl;
cout<<"aa.temp.bbi "<<aa.temp.bbi<<endl;
AA::BB bb;
cout<<"AA::BB.bbi "<<bb.bbi<<endl;
}
Copyright © Open Sky Technology |