0

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?

Community
  • 1
  • 1
johnbakers
  • 24,158
  • 24
  • 130
  • 258

3 Answers3

2

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.

Deduplicator
  • 44,692
  • 7
  • 66
  • 118
2

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.

Manuel Arwed Schmidt
  • 3,376
  • 2
  • 18
  • 28
0

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.

Ed Heal
  • 59,252
  • 17
  • 87
  • 127