CVFCD -- Calling Virtual Functions from Constructors and Destructor

From RAD Studio
Jump to: navigation, search

Go Up to C++ Audits

Description

In a constructor, the virtual call mechanism is disabled because overriding from derived classes has not yet happened. Objects are constructed from the base up, "base before derived". Therefore, you should not use virtual functions either in constructors or in destructors.

Destruction is done "derived class before base class", so virtual functions behave as in constructors. Only the local definitions are used, and no calls are made to overriding functions to avoid touching the (now destroyed) derived class part of the object.

Incorrect

 #include <iostream>
 #include <string>
 using namespace std;
 
 class B {
 public:
   B(const string& ss) { cout << "B constructor\n"; f(ss); }
   virtual void f(const string&) { cout << "B::f\n";}
 };
 
 class D : public B {
 public:
   D(const string& ss) :B(ss) { cout << "D constructor\n";}
   void f(const string& ss) { cout << "D::f\n"; s = ss; }
 private:
   string s;
 };
 
 int main() {
   D d("Hello");
 }

The program compiles and produces:

B constructor
B::f
D constructor

See Also