I know there is clear answer for this question: Base class constructor is called first, then derived class constructor is called.
But I don't fully understand the word "called". Does it mean the beginning of usage of the constructor, or the completion of usage of the constructor? In other word, there are two possible orders for the code below:
BaseClass constructor starts -> BaseClass constructor completes -> DerivedClass constructor starts -> DerivedClass constructor completes.
DerivedClass constructor starts -> BaseClass constructor starts -> BaseClass constructor completes -> DerivedClass constructor completes.
Which one should be the correct order? And if 1 is correct, how does the compiler know to call BaseClass constructor before we initialize a DerivedClass instance?
It seems case 2 is correct: "called" should mean the completion of constructor. A follow-up question is how about the destructor? I know the standard answer is "the destructor of derived class is called first". So which is the correct order for:
- DerivedClass destructor starts
- DerivedClass destructor completes
- BaseClass destructor starts
- BaseClass destructor completes
Thanks
class BaseClass {
public:
BaseClass() {
cout << "BaseClass constructor." << endl;
}
};
class DerivedClass : public BaseClass {
public:
DerivedClass() : BaseClass() {
cout << "DerivedClass constructor." << endl;
}
};
int main() {
DerivedClass dc;
}