I was testing which constructors are called in when a derived and then base class objects are created. My program couted 0 if it was the base class and 1 if it was the base class. I ran it and it returned 01 for the derived class and 0 for the base class. The derived class surprised me greatly because it seems as thought it calls the base class and then the derived class. Is this information correct?

The order of class object constuction (reduced C++ rules, apply recursively):

1. direct base class(es) constructor(s)
2. this nonstatic data member(s) constructor(s)
3. this constructor

Revert the order for destruction.

Try this:

class Member { public:
Member(const char* where = ""):whom(where) {
        cout << "Member " << where << " ctor\n";
    }
    ~Member() { cout << "Member " << whom << " dtor\n"; }
    std::string whom;
}; 

class Base { public:
    Base():m("Base") { cout << "Base ctor\n"; }
    ~Base(){ cout << "Base dtor\n"; }
    Member m;
};
class Derived: public Base
{ public:
Derived():mm("Derived") { cout << "Derived ctor\n"; }
    ~Derived(){ cout << "Derived dtor\n"; }
    Member mm;
};

Yes but doesn't it seem terribly inefficient to call all of the constructors in that order automatically? Is there any way to stop it?

Yes but doesn't it seem terribly inefficient to call all of the constructors in that order automatically? Is there any way to stop it?

Yes, of course: stop using this inefficient ;) language C++, switch to Visual Basic (or better to Fortran 66)...
Yet another way to go: never declare class variables and don't use operator new. No declarations - no constructors...

Also, What happens if the constructor tries to initializ a variable that wasn't inherited?

Also, What happens if the constructor tries to initializ a variable that wasn't inherited?

???
Can you give an example of this mysterious case?

This article has been dead for over six months. Start a new discussion instead.