Are parent class constructors called before initializing variables, or will the compiler initialize the variables of the class first?
For example:
c
Yes, the base class is initialized before the members of the derived class and before the constructor body executes.
In a non-delegating constructor, initialization proceeds in the following order:
— First, and only for the constructor of the most derived class (1.8), virtual base classes are initialized in the order they appear on a depth-first left-to-right traversal of the directed acyclic graph of base classes, where “left-to-right” is the order of appearance of the base classes in the derived class base-specifier-list.
— Then, direct base classes are initialized in declaration order as they appear in the base-specifier-list (regardless of the order of the mem-initializers).
— Then, non-static data members are initialized in the order they were declared in the class definition (again regardless of the order of the mem-initializers).
— Finally, the compound-statement of the constructor body is executed.
Yes, the parent constructor is always called before the derived class. Otherwise, the derived class couldn't "alter" something set by the parent class.
think of derived class as extra addition or extension of its base class, addition so it adds to something (this something must already exists). then, another issue is initialization of members. here, you provided default constructor
public:
parent() : a(123) {};
so the member will be default initialized with 123 even if you create parent this way:
parent p;
if there was no default constructor that initializes object with value
class parent {
public:
int a;
};
than what will be by default in member depends, if the class is P.O.D then int will be default initialized to 0, but if it is not, i.e. you provide more members such as string or vector
class parent {
public:
int a;
std::string s;
std::vector<int> v;
};
int will have random value if there is no default constructor that initializes it.
Yes,construction of objects starts from the parent class and comes to child classes, so the constructor calls are in that order. In case of destruction, this is exactly opposite.
Just as some advice, you can usually just test things like this out yourself if you're not sure:
#include <iostream>
using namespace std;
class parent {
protected:
int a;
public:
parent() : a(123) { cout << "in parent(): a == " << a << endl; };
};
class child : public parent {
int b;
public:
// question: is parent constructor done before init b?
child() : b(456), parent() { cout << "in child(): a == " << a << ", b == " << b << endl; };
};
int main() {
child c;
return 0;
}
prints
in parent(): a == 123
in child(): a == 123, b == 456