What are the rules for calling the superclass constructor?

前端 未结 10 2335
甜味超标
甜味超标 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:52

    Base class constructors are automatically called for you if they have no argument. If you want to call a superclass constructor with an argument, you must use the subclass's constructor initialization list. Unlike Java, C++ supports multiple inheritance (for better or worse), so the base class must be referred to by name, rather than "super()".

    class SuperClass
    {
        public:
    
            SuperClass(int foo)
            {
                // do something with foo
            }
    };
    
    class SubClass : public SuperClass
    {
        public:
    
            SubClass(int foo, int bar)
            : SuperClass(foo)    // Call the superclass constructor in the subclass' initialization list.
            {
                // do something with bar
            }
    };
    

    More info on the constructor's initialization list here and here.

提交回复
热议问题