7

Possible Duplicate:
Calling virtual functions inside constructors

main.cpp

#include <iostream>

class BaseClass {

    public:

    BaseClass() {
        init();
    }

    virtual ~BaseClass() {
        deinit();
    }

    virtual void init() {
        std::cout << "BaseClass::init()\n";
    }

    virtual void deinit() {
        std::cout << "BaseClass::deinit()\n";
    }

};

class SubClass : public BaseClass {

    public:

    virtual void init() {
        std::cout << "SubClass::init()\n";
    }

    virtual void deinit() {
        std::cout << "SubClass::deinit()\n";
    }

};

int main() {
    SubClass* cls = new SubClass;
    delete cls;
    return 0;
}

Why is init() and deinit() not properly overriden and the BaseClasses' methods are called instead of the SubClasses ones? What are the requirements to make it work?

BaseClass::init()
BaseClass::deinit()
Community
  • 1
  • 1
Niklas R
  • 16,299
  • 28
  • 108
  • 203
  • @LightnessRacesinOrbit: Sorry for that. I didn't directly associate the problem with the constructor and destructor, which I guess was why I didn't find this question. – Niklas R Jan 31 '13 at 13:39
  • I guess the justification is that `SubClass`'s constructor is allowed to assume that `BaseClass` is entirely constructed when it is executing. Similar for the destructor. – Alex Chamberlain Jan 31 '13 at 13:42

2 Answers2

5

They are overridden just fine.

But you've invoked them from the base constructor, and when the base constructor is executing, the derived part of the object does not yet exist.

So this is a largely a safety feature, and it's mandated by the C++ standard.

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
5

Because you are calling a virtual method inside a constructor. While constructing Base class the derived one (SubClass) isn't still constructed, so actually it doesn't still exist.

It's generally a good practice to avoid calling virtual methods inside constructors.

Heisenbug
  • 38,762
  • 28
  • 132
  • 190