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.
Problem Statement: Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses. Example…
Given an integer A. Compute and return the square root of A. If A is…
Given a zero-based permutation nums (0-indexed), build an array ans of the same length where…
A heap is a specialized tree-based data structure that satisfies the heap property. It is…
What is the Lowest Common Ancestor? In a tree, the lowest common ancestor (LCA) of…