Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does C++ require you to initialize base class members from its derived class?

class Base {
public:
    int a;
    Base():a(0) {}
    virtual ~Base();
}
class Derived : public Base {
public:
    int b;
    Derived():b(0) {
        Base* pBase = static_cast<Base*>(this);
        pBase->Base();
    }
    ~Derived();
}

Is the call to the base class constructor necessary or does c++ do this automatically? e.g. Does C++ require you to initialize base class members from any derived class?

like image 734
Worryn Ashtrod Avatar asked Jan 23 '26 05:01

Worryn Ashtrod


1 Answers

The base class's constructor will automatically be called before the derived class's constructor is called.

You can explicitly specify which base constructor to call (if it has multiple) using initialization lists:

class Base {
  public:
    int a;
    Base():a(0) {}
    Base(int a):a(a) {}
};
class Derived {
  public:
    int b;
    Derived():Base(),b(0) {}
    Derived(int a):Base(a),b(0) {}
};
like image 64
Andrew Rasmussen Avatar answered Jan 24 '26 23:01

Andrew Rasmussen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!