Virtual base Class

Consider Example of Hybrid Inheritance

Virtual Base Class

Here, BASE is a base class from which two classes DERIVED1 and DERIVED2 are derived. Now class DERIVED3 is derived from two classes DERIVED1 and DERIVED2. In this case the public data member of class BASE is inherited in class DERIVED1 and DERIVED2. Class DERIVED3 is derived from two base classes DERIVED1 and DERIVED2 so the data member of class BASE is inherited into class DERIVED3 twice, one through class DERIVED1 and one through class DERIVED2.
Thus public and protected data member of class BASE inherited twice in class DERIVED3. To avoid duplication of data member of common base class we have to declare it as a virtual base class.
The general syntax for declaring common base class as virtual is given below:
class A
{
………
………
};
class B : virtual public A
{
………
………
};
class C : virtual public A
{
………
………
};
class D : public B, public C
{
………
………
};

     

#include <iostream.h>
class student
{
      int r_no;
      char name[20];
      public:
      void instudent()
      {
            cout<<”Enter Roll Number:”;
            cin>>r_no;
            cout<<”Enter Name:”;
            cin>>name;
      }
      void outstudent()
      {
            cout<<”Roll Number:”<<r_no<<endl;
            cout<<”Name:”<<name<<endl;
      }
};
class TW: virtual public Student
{
      int tmark;
      public:
      void intmark()
      {
            cout<<”Enter Term work mark:”;
            cin>>tmark;
      }
      void outtmark()
      {
            cout<<”Term Work Mark:”<<tmark;
      }
};
class EXT: virtual public Student
{
      int emark;
      public:
      void inemark()
      {
            cout<<”Enter External mark:”;
            cin>>emark;
      }
      void outemark()
      {
            cout<<”External Mark:”<<emark;
      }
};
class Result: public TW, public EXT
{
      int total;
      public:
      void displayResult ()
      {
            total = tmark + emark;
            outstudent ();
            outtmark();
            outemark ();
            cout<<”Total=”<<total;
      }
}
int main ()
{
      Result R[60];
      int i;
      for (i=0;i<60;i++)
      {
            R[i].instudent ();
            R[i].intmark ();
            R[i].inemark();
      }
      for (i=0;i<60;i++)
      {
            R[i].display ();
      }
      return 0;
}

Download Projects


Download Programs