In C++, you cannot call a virtual / overriden method from a constructor.
Now, there is a good reason you can do this. As a "best practice in software", you should avoid calling additional methods from your constructor, even non virtual, as possible.
But, there is always an exception to the rule, so you may want to use a "pseudo constructor method", to emulate 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" for only fields structures, and "class" for structures with fields, methods, constructors, ...