Thursday, March 21, 2013

Virtual Base Class – C++.



In class hierarchies we have many common things and  the common code is implemented in a base class. Methods and variables and other objects accessed through multiple-inheritance. Base class have only one instance, there is no ambiguity when accessing these names. So,  virtual base classes offer a way to save space and avoid uncertainties in class hierarchies that use multiple inheritance.


Example :

#include <iostream.h>

  class Stud_det
      {
          protected:
             int Roll;
             char name[20];
          public:
             void getData();
             void showData();
      };
  void Stud_det::getData()
      {
          cout<<"\n\tRoll No? ";
          cin>>Roll;
          cout<<"\n\tStudent Name? ";
          cin>>name;
      }
  void Stud_det::showData()
      {
          cout<<"\n\n\n\t\tStudent Details";
          cout<<"\n\n\tRoll No:"<<Roll<<"  Name : "<<name;
      }
  class Exam:virtual public Stud_det
      {
          protected:
             int marks[5];
          public:
             void getMarks();
             void showMarks();
      };
  void Exam::getMarks()
      {
          char Sub[5][10]={"Eng","Maths","Phy","Chem","Comp"};
          cout<<"\n\tMarks For\n";
          for(int i=0;i<5;i++)
             {
                 cout<<"\n\t"<<Sub[i]<<"? ";
                 cin>>marks[i];
             }
      }
  void Exam::showMarks()
      {
          cout<<"\n\tMarks Obtained\n";
          char Sub[5][10]={"Eng","Maths","Phy","Chem","Comp"};
          for(int i=0;i<5;i++)
             {
                 cout<<"\n\t"<<Sub[i]<<"  :  "<<marks[i];
             }
      }
  class Extra_Curr:public virtual Stud_det
      {
          protected:
             int Point;
          public:
          void getPoint();
          void showPoint();
      };
  void Extra_Curr::getPoint()
      {
          cout<<"\n\tPoints For Extra Curricular Activites : ";
          cin>>Point;
      }
  void Extra_Curr::showPoint()
      {
          cout<<"\n\tPoints For Extra Curricular Activites : ";
          cout<<Point;
      }

  class Result:public Exam,public Extra_Curr
      {
          public:
             void showResult();
      };
  void Result::showResult()
      {
          int Tmarks=0;
          float Avg=0;
          for(int i=0;i<5;i++)
             {
                 Tmarks=Tmarks+marks[i];
             }
          Tmarks+=Point;
          Avg=Tmarks/5.0;
          cout<<"\n\tTotals : "<<Tmarks;
          cout<<"\n\tAggregrate : "<<Avg;
      }

  int main()
      {
          Result Rs;
          Rs.getData();
          Rs.getMarks();
          Rs.getPoint();
          Rs.showData();
          Rs.showMarks();
          Rs.showResult();
          return 0;
      }


No comments: