In C ++, you cannot call the virtual / overriden method from the constructor.
Now there is a good reason why you can do this. As a โbest practice in softwareโ, you should avoid calling additional methods from your constructor, not even virtual as much as possible.
But there is always an exception to the rule, so you can use the "pseudo constructor method" to mimic them:
#include <iostream> class base { // <constructor> base() { // do nothing in purpouse } // </constructor> // <destructor> ~base() { // do nothing in purpouse } // </destructor> // <fake-constructor> public virtual void create() { // move code from static constructor to fake constructor std::cout << value() << std::endl; } // </fake-constructor> // <fake-destructor> public virtual void destroy() { // move code from static destructor to fake destructor // ... } // </fake-destructor> public virtual const int value() const { return 0; } public virtual void DoSomething() { // std:cout << "Hello World"; } }; class derived : public base { // <fake-constructor> public override void create() { // move code from static constructor to fake constructor std::cout << "Im pretending to be a virtual constructor," << std::endl; std::cout << "and can call virtual methods" << std::endl; } // </fake-constructor> // <fake-destructor> public override void destroy() { // move code from static destructor to fake destructor std::cout << "Im pretending to be a virtual destructor," << std::endl; std::cout << "and can call virtual methods" << std::endl; } // </fake-destructor> public virtual const int value() const { return 1; } }; int main(void) { // call fake virtual constructor in same line, after real constructor derived* example = new example(); example->create(); // do several stuff with your objects example->doSomething(); // call fake virtual destructor in same line, before real destructor example->destroy(); delete example(); }
As a plus, I recommend programmers to use "struct" only for field structures and "class" for structures with fields, methods, constructors, ...
umlcat Mar 28 '11 at 17:10 2011-03-28 17:10
source share