I have a question about implicit and explicit calls to the base constructor. If we have a class hierarchy:
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 lectures, the call to “Baby” is basically like this:
std::string babyname = "Robert";
int nappies = 5;
Baby baby(babyname, nappies);
Invokes the following:
- Since an explicit call to Person is made in the Baby initialization list: The Baby initialization list is received , but
no_of_nappiesinitialized. - Next, a call to the Person constructor is created and the Person initialization list is called . Initialized
m_name. - Then the body of the constructor Person is called.
- The body of the child’s constructor is finally called.
This makes sense, however, what if there were implicit calls made to the default constructor of the parent class, for example:
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; }
};
, . , Bicycle bike; :
- Vehicle default Bike. .
- , ,
m_no_wheels 0. - .
- Bicycle , ,
m_is_locked false. - .
- , ?
, , , , , , , .
, !
: , , .