I have a question about implicit and explicit calls to a base constructor. If we have a class hierarchy like this:
class Person{
protected:
std::string m_name;
public:
Person(std::string& _name) : m_name(_name){std::cout << "A person is being constructed." << std::endl;}
};
class Baby : public Person{
private:
int m_no_of_nappies;
public:
Baby(std::string& _name, int& _no_of_nappies) : m_no_of_nappies(_no_of_nappies), Person(_name) {std::cout << "A baby is being constructed." << std::endl ;}
};
According to my lecture notes, a call to 'Baby' in the main, like so:
std::string babyname = "Robert";
int nappies = 5;
Baby baby(babyname, nappies);
Causes the following to happen:
- As an explicit call to Person is made in Baby's initialisation list: Baby's initialisation list gets called, and the
no_of_nappies
is initialised. - Next, a call to Person's constructor is made and Person's initialisation list is called. The
m_name
is initialised. - Person's constructor body is then called.
- Baby's constructor body is finally called.
This makes sense, however, what about if there were implicit calls made to the default constructor of a parent class, like so:
class Vehicle{
protected:
int m_no_wheels;
public:
Vehicle() : m_no_wheels(0) { std::cout << "A vehicle is being constructed." << std::endl; }
};
class Bicycle : public Vehicle{
protected:
bool m_is_locked;
public:
Bicycle() : m_is_locked(false) { std::cout << "A bicycle is being constructed." << std::endl; }
};
This is the part that I'm not so sure about. My best guess is that a call to Bicycle bike;
in the main has the following effect:
- An implicit call is made to Vehicle's default constructor from Bike. Before the Bike's initialisation list is called.
- As vehicle doesn't inherit from anything, Vehicle's initialisation list is called where it initialises
m_no_wheels
to0
. - Vehicle's constructor body is called.
- We return to Bicycle and now its initialisation list is called, initialising
m_is_locked
tofalse
. - Bike's constructor body is called.
Could somebody please explain if my reasoning behind the implicit call is correct?
The main difference, in my opinion, is the fact that with an explicit reference to the base constructor, the child class' initialisation list is always hit first in order to call that base constructor - however, with an implicit call, the top most parent's initialisation list is always hit first.
Thank you, and much appreciated!
Edit: I'm asking specifically if the order changes, depending on an implicit or explicit call to the parent class.