In: Computer Science
Write a Simple C++ Code to show that the Constructors of Composed Classes Execute before Container Classes.
SOLUTION :
In this example Car class is the Container class which contains engine thus engine is the Composed class.
Constructors are created for both the classes and composed object variable is declared in the container class Car.
When the container class is called from the main method(invoking constructos by creating object of Car),it is observed that the constructor of Composed class Engine is executed first and then the constructor of Container class is executed.
PROGRAM :
#include <iostream>
using namespace std;
// composed object class
class Engine {
public:
Engine() {
cout<<"Constructor of composed class Engine\n";
}
~Engine() {
cout<<"Destructor of Engine class\n";
}
};
// container class
class Car{
private:
// e is the composed object of Composed class Engine
Engine e;
public:
Car() {
cout<<"Constructor of container class
Car\n";
}
~Car() {
cout<<"Destructor of Car class\n";
}
};
int main() {
// creating object for container class Car
Car c;
return 0;
}
OUTPUT :