Implementing Constructors on Inheritance with using Keyword in C++
Since C++11, using Base::Base; lets a child class inherit the constructors of its parent instead of writing them again.
The using keyword is the new way (since C++11) to give a child class the constructors of its parent. These are called inheriting constructors.
#include <iostream>
#include <string>
class MyParent{
public:
MyParent(){
std::cout << "MyParent()" << std::endl;
}
MyParent(std::string inp){
std::cout << "MyParent(" << inp << ")" << std::endl;
}
~MyParent(){
std::cout << "~MyParent()" << std::endl;
}
};
class MyChild : public MyParent{
public:
using MyParent::MyParent;
// inherits the constructors of MyParent
};
int main()
{
MyChild p{"Hello"};
return 0;
}
The copy and move constructors of the parent are not inherited; the child gets its own implicit ones as usual. Members that the child class adds are not initialized by the inherited constructors, so give them a default member initializer.