What are the rules for calling the superclass constructor?

前端 未结 10 2339
甜味超标
甜味超标 2020-11-21 23:18

What are the C++ rules for calling the superclass constructor from a subclass one?

For example, I know in Java, you must do it as the first line of the subclass cons

10条回答
  •  没有蜡笔的小新
    2020-11-21 23:58

    If you have default parameters in your base constructor the base class will be called automatically.

    using namespace std;
    
    class Base
    {
        public:
        Base(int a=1) : _a(a) {}
    
        protected:
        int _a;
    };
    
    class Derived : public Base
    {
      public:
      Derived() {}
    
      void printit() { cout << _a << endl; }
    };
    
    int main()
    {
       Derived d;
       d.printit();
       return 0;
    }
    

    Output is: 1

提交回复
热议问题