Day_Dreamer
Day_Dreamer

Reputation: 3373

calling a parent constructor C++

Is there any advantage to calling the parent constructor explicitly in the derived class constructor?

is this:

LockableDoor :: LockableDoor() : Door(), locked_(true) { }

is different from this:

LockableDoor :: LockableDoor() : locked_(true) { }

somehow?

Upvotes: 1

Views: 131

Answers (3)

ravi
ravi

Reputation: 10733

If it's a default constructor you want then you can leave it as compiler would automatically call it for you. But it's good for readability to explicitly call that constructor.

Upvotes: 1

Eugene
Eugene

Reputation: 71

This just provides the way you select appropriate parent constructor and pass parameters to it. No other advantages. In your example there is no difference between 2 lines.

Upvotes: 3

Blindy
Blindy

Reputation: 67380

It's not different, but the answer to your question is yes, it is sometimes advantageous to call parent constructors. That's the case when you want to call something other than the constructor with no arguments (especially if you have none of those):

A::A(int) {}
B::B(int i): A(i) {}       // derived from A

Upvotes: 1

Related Questions