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()
SubClass
's constructor is allowed to assume thatBaseClass
is entirely constructed when it is executing. Similar for the destructor. – Gorski