Home > Enterprise >  Base class default constructor in derived class constructor initializer list
Base class default constructor in derived class constructor initializer list

Time:09-13

I have seen a lot of times people adding the default constructor of base class in the derived class constructor initializer list like so

DerivedClass::DerivedClass(int x) : BaseClass(), member_derived(x)
{
    //Do something;
}

Derived class constructor by default calls the default constructor of base class. Is the BaseClass() in the above initializer list redundant?

CodePudding user response:

It depends on declaration of base class. Constructor of derived class actually initializes base class. It involves default constructor call if such is present. If base class is trivial, it wouldn't be initialized. Consider this code:

#include <iostream>

struct Base {
   int c;
};

class Derived : public Base {
public:
   Derived() : Base()
   {}
};

int main()
{
    Derived d;
    std::cout << d.c << std::endl;
}

If you would comment : Base() out, you may get compiler warning, or a random value printed.

prog.cc: In function 'int main()':
prog.cc:17:20: warning: 'd.Derived::<anonymous>.Base::c' is used uninitialized [-Wuninitialized]
   17 |     std::cout << d.c << std::endl;
      |                    ^
prog.cc:16:13: note: 'd' declared here
   16 |     Derived d;

in this case : Base() ensures value initialization of Base

CodePudding user response:

It's redundant to explicitly mention the base class default constructor in a derived class's initialization list. But if doing so makes you feel good, feel free to do it.

  • Related