If we inherit a class from another class and create an object of the derived class, it is obvious that the derived class’s default constructor will be invoked, but first, the default constructors of all base classes will be invoked.
The data members and member functions of the base class are automatically included in the derived class based on the access specifier, but the definition of these members is only available in the base class. When we create an object of a derived class, all of its members must be initialized, but the inherited members in the derived class can only be initialized by the base class’s constructor because their definition exists only in the base class. This is why the base class’s constructor is called first to initialize all inherited members.
#include<iostream>
using namespace std;
//base class
class Device{
public:
Device(){
cout<<"Constructor: Device\n";
}
~Device(){
cout<<"Destructor : Device\n";
}
};
//derived class
class Mobile:public Device{
public:
Mobile(){
cout<<"Constructor: Mobile\n";
}
~Mobile(){
cout<<"Destructor : Mobile\n";
}
};
//derived class
class Android:public Mobile{
public:
Android(){
cout<<"Constructor: Android\n";
}
~Android(){
cout<<"Destructor : Android\n";
}
};
int main()
{
Android _android; // create the object that will call required constructors
return 0;
}
Constructor: Device
Constructor: Mobile
Constructor: Android
Destructor : Android
Destructor : Mobile
Destructor : Device
Important points:
Note: also read about Types of Inheritance in C++
If you like my post please follow me to read my latest post on programming and technology.
https://www.instagram.com/coderz.py/
https://www.facebook.com/coderz.py
Staying up to the mark is what defines me. Hi all! I’m Rabecca Fatima a keen learner, great enthusiast, ready to take new challenges as stepping stones towards flying colors.
You are given a stream of elements that is too large to fit into memory.…
The formula for the area of a circle is given by πr². Use the Monte…
Given an integer k and a string s, write a function to determine the length…
There is a staircase with N steps, and you can ascend either 1 step or…
Build an autocomplete system that, given a query string s and a set of possible…
Design a job scheduler that accepts a function f and an integer n. The scheduler…