I have looked at similar queries but I seem to be getting myself lost. I have a simple example, so please consider the following:
#include <iostream>
using namespace std;
class Animal
{
public:
Animal() {cout << "Animal" << endl;}
};
class Cat : public Animal
{
public:
Cat() {cout << "Cat" << endl;};
};
int main()
{
Cat c;
return 0;
}
When the program runs, it displays
Animal
Cat
My question is now this: Which constructor is actually called first. Is Cat() called and then Cat() calls Animal() before it executes its contents OR does the compiler/program look at Cat(), see that it's an Animal() and calls Animal() first then Cat()?
The Animal constructor is executed before the Cat constructor body as part of the initialization of the Cat object when the Cat constructor is called. It's the same as if you had done this explicitly in an initialization list:
If you want to pass arguments to a base class constructor, then you must do it explicitly as above, otherwise the default constructor (one with no parameters) is called for you. In either case, the base class constructor completes before initialization of the derived object continues.