inheriting constructor
As the name suggested that we can inherit the base class constructor in derive class and we can use them.
How to use inheriting constructor:
//In Derive class, use the "using" keyword like below using baseClassName::baseClassName; //inheriting constructor
Important points:
- We should use the inheriting constructor in derived class which has no data members.
- If derived class has own data members and we are using inheriting constructor then use “in class member initialization” for own data members.
- If we are using inheriting constructor and writes own constructors of derived class then these derived class constructors will overwrite inheriting constructors.
- When we use inheriting constructor then compiler generated the same copy of base class constructors in derived class.
source code with example:
/* Program:Inheritance Constructor Author: Alpha Master Date: 12 March 2021 */ //Header File #include<iostream> class base { int m_a; public: base() { m_a = 0; std::cout<<"default base constructor"<<std::endl; } base(int tmp) { m_a = tmp; std::cout<<"parameterized base constructor"<<std::endl; } base(const base& tmpObj) { m_a = tmpObj.m_a; std::cout<<"copy base constructor"<<std::endl; } ~base() { m_a = 0; std::cout<<"base destructor"<<std::endl; } void print() { std::cout<<"A:"<<m_a<<std::endl; } }; class derived: base { int m_b{5}; //in class member initialization using base::base; //inheriting constructor public: void print() { std::cout<<"B:"<<m_b<<std::endl; } }; int main() { std::cout<<"Inheritance Constructor"<<std::endl; base obj(10); obj.print(); derived obj2; obj2.print(); return 0; }
Output:
Inheritance Constructor parameterized base constructor A:10 default base constructor B:5 base destructor base destructor
Conclusion: I would suggest not to use this feature and restrict the use of inheriting constructor to a class which has no data members.