nSv23
nSv23

Reputation: 439

calling Base class constructor vs initializing member variables in Child class

The Parent class is an abstract class. Here _isDone, _prob are protected variables of Parent class, that are inherited by Child.

What is the difference between using:

Child::Child(int _classType) : Parent(false, 1.0f) for initializing the variables of the Parent class.

vs.

Child::Child(int _classType) 
{
    _isDone = false;
    _prob = 1.0f;
}

I feel it is easier to use the second rather than the first. Any reason to use the first.

Upvotes: 1

Views: 102

Answers (1)

for_stack
for_stack

Reputation: 22946

Short answer: The first one is initialization, while the second one is assignment.

The first one initializes _isDone and _prob with Parent's constructor. However, when you are using the second one, _isDone and _prob are initialized with Parent's default constructor, and then they are assigned new values in Child constructor's function body.

The first one is better for the following reasons:

  1. If Parent doesn't have default constructor, the second one CANNOT work.
  2. The first one is more efficient, especially when the data member is a 'very large' object, whose default constructor is very expensive. Since the first one calls default constructor for the data member, and then calls operator= to assign a new value, while the second one just calls a proper constructor. The default constructor is redundant.
  3. Personally, I don't think it's a good idea to access the Parent's data member directly: coupling increases between Parent and Child.

Upvotes: 1

Related Questions