0

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?

2
Contributors
5
Replies
6
Views
7 Years
Discussion Span
Last Post by ArkM
0

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;
};
0

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?

0

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...

0

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

0

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.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.