CRITICAL
Rule Definition
Invoking virtual functions in a constructor/destructor always invokes the function for the class under construction/destruction, even when the constructor is invoked as part of the construction of a derived Class. This behavior is not often what was expected.
Remediation
If you want virtual function call behavior at construction time, it must be done post construction. Several idioms exist to help you do that, however none of them are perfect ("C++ coding standards":http://www.gotw.ca/publications/c++cs.htm details some options).
Violation Code Sample
class Mother
{
public:
Mother() { display(); }
private:
virtual void display() { cout << "Mother function call\n"; }
};
class Child : public Mother
{
private:
virtual void display() { cout << "Child function call\n";}
};
int main()
{
Child child; // will display "Mother function call"
}
Fixed Code Sample
class Mother
{
public:
template <class T>
shared_ptr<T> create()
{
shared_ptr<T> result = make_shared<T>();
result->display();
return result;
}
protected:
Mother() { } // It is now protected, to prevent direct creation
private:
virtual void display() { cout << "Mother function call\n"; }
};
class Child : public Mother
{
protected:
Child() { } // It is now protected, to prevent direct creation
private:
virtual void display() { cout << "Child function call\n";}
};
Reference
Effective C++ (Scott Meyers): "Item 9: Never call virtual functions during construction or destruction":http://www.artima.com/cppsource/nevercall.html
C++ coding standard (Sutter/Alexandrescu): "Item 49":http://www.gotw.ca/publications/c++cs.htm
Related Technologies
C++
Technical Criterion
Programming Practices - OO Inheritance and Polymorphism
About CAST Appmarq
CAST Appmarq is by far the biggest repository of data about real IT systems. It's built on thousands of analyzed applications, made of 35 different technologies, by over 300 business organizations across major verticals. It provides IT Leaders with factual key analytics to let them know if their applications are on track.