Géry Ogam
Géry Ogam

Reputation: 8027

Why is a derived constructor forced to call a base constructor in C++?

Why is a derived class constructor forced to call a base class constructor in C++ (either implicitly or explicitly)?

For example:

#include <iostream>

struct B1 {
    B1() { std::cout << "B1"; }
};

struct B2 {
    B2(int x) { std::cout << "B2"; }
};

struct D1: B1 {
    D1() { std::cout << "D1"; }  // implicitly calls B1::B1
};

struct D2: B2 {
    D2(int x): B2(x) { std::cout << "D2"; }  // explicitly calls B2::B2
};

int main() {
    D1 d1 {};  // prints B1D1
    D2 d2 {5};  // prints B2D2
    return 0;
}

Upvotes: 3

Views: 363

Answers (3)

One of the staples of C++ is the importance of deterministic initialization and deinitialization for user defined types. It's arguably the most compelling feature of the language.

So the compiler is made to enforce the initialization and deinitialization whenever it can. C++ will not let us get a half-baked object easily. That's a good thing when maintaining class invariants. We want the compiler's help to ensure those are maintained.

Other languages (such as Python, where initialization of bases needs to be explicit) may choose other design guidelines, but C++ follows its own.

Upvotes: 2

Sprite
Sprite

Reputation: 3763

A derived class is going to inherit the base class, which means that the functions of the base class need to be used in this derived class. Otherwise the inheritance becomes meaningless.

If the constructor of the base class is not called, the member functions of the base class may not work.

Upvotes: 0

Aramakus
Aramakus

Reputation: 1920

Derived class inherits all members of the base class. When you create an instance of a derived class, base class constructor is called to initialize respective members.

Upvotes: 0

Related Questions