I know the basic idea of composition that the composition has "have" relationship.But when it came to implement the idea of composition something went wrong,Till now i didn't figure out the object and constructor call of another class in the base class. Please help me on this regard.
Composition means that the contained class object does not exist beyond the lifetime of the outer class(which contains it) object.
#include <iostream>
class MyClass
{
public:
MyClass(){std::cout<<"\nMyClass";}
~MyClass(){std::cout<<"\n~MyClass";}
};
class MySecClass
{
MyClass obj;
public:
MySecClass(){std::cout<<"\nMySecClass";}
~MySecClass(){std::cout<<"\n~MySecClass";}
};
int main()
{
MySecClass obj;
return 0;
}
Output:
MyClass
MySecClass
~MySecClass
~MyClass
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.