C++ では、コンストラクターから仮想/オーバーライド メソッドを呼び出すことはできません。
さて、これができるのには十分な理由があります。「ソフトウェアでのベスト プラクティス」として、非仮想であっても、コンストラクターから追加のメソッドをできるだけ呼び出さないようにする必要があります。
ただし、ルールには常に例外があるため、「疑似コンストラクター メソッド」を使用してそれらをエミュレートすることをお勧めします。
#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();
}
プラスとして、プログラマーはフィールド構造のみに「構造体」を使用し、フィールド、メソッド、コンストラクターなどを含む構造体には「クラス」を使用することをお勧めします...