Inherited Constructors in C++

前端 未结 2 1117
误落风尘
误落风尘 2021-01-07 02:20

I\'m trying to practice Inheriting Constructors in C++. I have compiled and run following program in gcc and it\'s working fine.

#include<         


        
2条回答
  •  没有蜡笔的小新
    2021-01-07 02:39

    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) {}
    };
    

提交回复
热议问题