I\'m trying to practice Inheriting Constructors in C++. I have compiled and run following program in gcc and it\'s working fine.
#include<
The default constructors are being called because Derived
inherits from Base1
and Base2
. Both of those bases need to be constructed when you construct a Derived
object. So when you do
Derived d1(3);
You call Base1(int i)
. Now you need to construct the Base2
part and since you do not specify how, the compiler default constructs it. The same thing happens in
Derived d2("hello");
Since you do not specify how to construct the Base1
part in the constructor the compiler default constructs it for you. Then Base2(const string& s)
is called to construct the Base2
part.
Essentially what you have is
class Derived :public Base1, public Base2
{
public:
Derived(int n) : Base1(n), Base2() {}
Derived(const std::string& str) : Base1(), Base2(str) {}
};