Monday, 9 March 2015

Virtual base class initialization and the most derived classes


Virtual base class initialization and the most derived classes with examples:

That means any class, no matter how far away it is from the virtual base, is responsible for initializing it.

See the working example to understand more about the most derived classes.

#include "stdafx.h"
#include <iostream>
#include <vector>
using namespace std;
class MyBase
{
public:
  MyBase (int)
     { }
  virtual char* VirtualFunc () const = 0;
  virtual ~MyBase ()
    { }
};
class Derived1: virtual public MyBase
{
public:
  Derived1 () : MyBase (1)
    {}
  char* VirtualFunc () const
    { return "Derived1"; }
};
class Derived2 : virtual public MyBase
{
public:
  Derived2 () : MyBase(2)
    { }
  char* VirtualFunc  () const
    { return "Derived2"; }
};
class Derived3 : public Derived1, public Derived2
{
public:
  Derived3 () : MyBase(3)
    {}
  char* VirtualFunc () const
   { return Derived1::VirtualFunc (); }
};
class Derived4 : public Derived3
{
public:
  Derived4 () : MyBase (4)
    {}
};
int main ()
{
  vector<MyBase*> vecBase;
  vecBase.push_back (new Derived1);
  vecBase.push_back (new Derived2);
  vecBase.push_back (new Derived3);
  vecBase.push_back (new Derived4);
  for (int iInd = 0; iInd < vecBase.size (); iInd++)
    { cout << vecBase[iInd]->VirtualFunc () << endl; }
 getchar ();
 return 0;
}

The ouput of the above program is
Derived1

Derived2

Derived1

Derived1


As you would expect, both Derived1 and Derived2 must initialize MyBase in their constructor. But so must Derived3 and Derived4, even though they are more than one layer away! That’s because each one in turn becomes the most-derived class. The compiler can’t know whether to use Derived1’s initialization of MyBase or to use Derived2’s version. Thus you are always forced to do it in the most-derived class.

In the previous example, MyBase is the most-derived class inside the MyBase constructor. Inside the Derived1 constructor, Derived1 is the most-derived class, and inside the Derived3 constructor, Derived3 is the most-derived class.

When you are using a virtual base class, the most-derived constructor is responsible for
initializing that virtual base class.

No comments: