Inheritance/Polymorphism  «Prev  Next»
Lesson 10 C++ Virtual Functions
Objective This page contains several guidelines for virtual functions along with several rules.
List several rules for working with virtual functions.
Here are several rules and guidelines for working with virtual functions:
  1. Only nonstatic member functions can be virtual.
  2. The virtual characteristic is inherited. Thus, the derived class function is automatically virtual, and the presence of the virtual keyword is usually omitted.
  3. Constructors cannot be virtual.
  4. Destructors can be virtual. As a rule of thumb, any class having virtual functions should have a virtual destructor.

In C++, a complete object is constructed one base class at a time.
If we have a base class B and a class D derived from B. When constructing a D object, while executing B's constructor, the dynamic type of the object under construction is B. In particular, a call to a virtual function B:: Fun will hit B's definition of Fun, regardless of whether D overrides it or not.
Calling a D member function when the D object's members have not even been initialized yet would lead to unpredictable results.
Only after the construction of B has completed is D'sconstructor body executed and its identity as a D established. As a rule of thumb, keep in mind that during B's construction there is no way to tell whether the B is a standalone object or a base part of some other further-derived object; virtually-acting virtual functions would be such a way.
a call from a constructor to a pure virtual function that is not defined at all has undefined behavior. Such code is therefore not only confusing, but it is also more fragile in the face of maintenance. On the other hand, some designs ask for post-construction, which is a virtual function that must be invoked right after the full object has been constructed.