When the object of a derived class is instantiated, discuss the chain of constructor calls that begin in the program. Discuss which constructor will be executed at the end. Can constructors be inherited?
When an object is created for a class, the default constructor of that class is automatically invoked to initialize the members of the class.
When object of derived class is instanciated, it is clear that the default constructor of the derived class will be invoked but before that the default constructor of all of the base classes will be invoke, i.e the order of invokation is that the base class’s default constructor will be invoked first and then the derived class’s default constructor will be invoked.
The data members and member functions of base class come automatically in derived class based on the access specifier. But the definition of these members exists in base class only. So when we create an object of derived class, all the members of derived class must be initialized whereas the inherited members in derived class can only be initialized by the base class’s constructor as the definition of these members exists in base class only. This is why the constructor of the base class is called first to initialize all the inherited members.
Only members are inherited, and a constructor is not considered a member.
To understand why constructors are not inherited, consider that inheritance in OOP is part of the mechanism that allows an object to be treated as another, more general object. This requires that all data members and all methods are inherited.
Get Answers For Free
Most questions answered within 1 hours.