What are the rules for calling the superclass constructor?

前端 未结 10 2107
甜味超标
甜味超标 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:50
    CDerived::CDerived()
    : CBase(...), iCount(0)  //this is the initialisation list. You can initialise member variables here too. (e.g. iCount := 0)
        {
        //construct body
        }
    
    0 讨论(0)
  • 2020-11-21 23:51

    If you have a constructor without arguments it will be called before the derived class constructor gets executed.

    If you want to call a base-constructor with arguments you have to explicitly write that in the derived constructor like this:

    class base
    {
      public:
      base (int arg)
      {
      }
    };
    
    class derived : public base
    {
      public:
      derived () : base (number)
      {
      }
    };
    

    You cannot construct a derived class without calling the parents constructor in C++. That either happens automatically if it's a non-arg C'tor, it happens if you call the derived constructor directly as shown above or your code won't compile.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-11-21 23:54

    In C++ there is a concept of constructor's initialization list, which is where you can and should call the base class' constructor and where you should also initialize the data members. The initialization list comes after the constructor signature following a colon, and before the body of the constructor. Let's say we have a class A:

    
    class A : public B
    {
    public:
      A(int a, int b, int c);
    private:
      int b_, c_;
    };
    

    Then, assuming B has a constructor which takes an int, A's constructor may look like this:

    
    A::A(int a, int b, int c) 
      : B(a), b_(b), c_(c) // initialization list
    {
      // do something
    }
    

    As you can see, the constructor of the base class is called in the initialization list. Initializing the data members in the initialization list, by the way, is preferable to assigning the values for b_, and c_ inside the body of the constructor, because you are saving the extra cost of assignment.

    Keep in mind, that data members are always initialized in the order in which they are declared in the class definition, regardless of their order in the initialization list. To avoid strange bugs, which may arise if your data members depend on each other, you should always make sure that the order of the members is the same in the initialization list and the class definition. For the same reason the base class constructor must be the first item in the initialization list. If you omit it altogether, then the default constructor for the base class will be called automatically. In that case, if the base class does not have a default constructor, you will get a compiler error.

    0 讨论(0)
  • 2020-11-21 23:55

    If you simply want to pass all constructor arguments to the base-class (=parent), here is a minimal example.

    This uses templates to forward every constructor call with 1, 2 or 3 arguments to the parent class std::string.

    Code

    Live-Version

    #include <iostream>
    #include <string>
    
    class ChildString: public std::string
    {
        public:
            template<typename... Args>
            ChildString(Args... args): std::string(args...)
            {
                std::cout 
                    << "\tConstructor call ChildString(nArgs="
                    << sizeof...(Args) << "): " << *this
                    << std::endl;
            }
    
    };
    
    int main()
    {
        std::cout << "Check out:" << std::endl;
        std::cout << "\thttp://www.cplusplus.com/reference/string/string/string/" << std::endl;
        std::cout << "for available string constructors" << std::endl;
    
        std::cout << std::endl;
        std::cout << "Initialization:" << std::endl;
        ChildString cs1 ("copy (2)");
    
        char char_arr[] = "from c-string (4)";
        ChildString cs2 (char_arr);
    
        std::string str = "substring (3)";
        ChildString cs3 (str, 0, str.length());
    
        std::cout << std::endl;
        std::cout << "Usage:" << std::endl;
        std::cout << "\tcs1: " << cs1 << std::endl;
        std::cout << "\tcs2: " << cs2 << std::endl;
        std::cout << "\tcs3: " << cs3 << std::endl;
    
        return 0;
    }
    

    Output

    Check out:
        http://www.cplusplus.com/reference/string/string/string/
    for available string constructors
    
    Initialization:
        Constructor call ChildString(nArgs=1): copy (2)
        Constructor call ChildString(nArgs=1): from c-string (4)
        Constructor call ChildString(nArgs=3): substring (3)
    
    Usage:
        cs1: copy (2)
        cs2: from c-string (4)
        cs3: substring (3)
    

    Update: Using Variadic Templates

    To generalize to n arguments and simplify

            template <class C>
            ChildString(C arg): std::string(arg)
            {
                std::cout << "\tConstructor call ChildString(C arg): " << *this << std::endl;
            }
            template <class C1, class C2>
            ChildString(C1 arg1, C2 arg2): std::string(arg1, arg2)
            {
                std::cout << "\tConstructor call ChildString(C1 arg1, C2 arg2, C3 arg3): " << *this << std::endl;
            }
            template <class C1, class C2, class C3>
            ChildString(C1 arg1, C2 arg2, C3 arg3): std::string(arg1, arg2, arg3)
            {
                std::cout << "\tConstructor call ChildString(C1 arg1, C2 arg2, C3 arg3): " << *this << std::endl;
            }
    

    to

    template<typename... Args>
            ChildString(Args... args): std::string(args...)
            {
                std::cout 
                    << "\tConstructor call ChildString(nArgs="
                    << sizeof...(Args) << "): " << *this
                    << std::endl;
            }
    
    0 讨论(0)
  • 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

    0 讨论(0)
提交回复
热议问题