johnbakers
johnbakers

Reputation: 24750

Do default constructors need to call base class default constructors?

Was reading this answer and it surprised me, the suggestion you must always call a base class constructor in the derived class constructor. What if you are working only with default constructors, consider:

class Bar : public Foo {
private:
int y;

public:
Bar() : Foo(), y(0) {
}

...

Is the call to Foo() really necessary here?

Upvotes: 0

Views: 433

Answers (3)

Ed Heal
Ed Heal

Reputation: 59997

You do not need to call them but I think it is a good idea in terms of readabilitty and also proves to the person reviewing the code that you understand that the class is derived.

Upvotes: 0

Deduplicator
Deduplicator

Reputation: 45654

You do not need to explicitly call a base class constructor in your constructor, in which case the compiler implicitly calls the default constructor, or you get a compile-time error, if none is callable.
Same applies to members who are non-POD.

An alternative is a member initialiser list only consisting of a delegation to another constructor of your class, thus creating a delegating constructor.

Upvotes: 2

Manuel Arwed Schmidt
Manuel Arwed Schmidt

Reputation: 3586

No, you don't. The reason why this is done is readability. It's clearer to read and might hint some IDEs helper logic like where the Baseclass::Baseclass() method is used.

Upvotes: 2

Related Questions