Google

Virtual Base class

Written on:December 30, 2012
Comments are closed





Virtual Base Class:

A virtual base class is one that is specified as virtual when it is inherited.  If the base class definition precedes the keyword virtual, then it is referred to as virtual base class.  If a situation arises, where the data members of a base class are inherited more than once to a derived class through different inheritance paths, as in the case of hybrid inheritance, the duplication is avoided by defining the base class as virtual.  When a base class is defined as virtual, then only one copy of the members of the base class is inherited, irrespective of the existence of different inheritance paths.

An example demonstrating the use of virtual base class is given below:

Example:

#include <iostream.h>
#include <conio.h>

class teacher
{
protected:
int s_id;
public:
void get_v()
{
cout<<“\nEnter school id>”;
cin>>s_id;
}
void put_v()
{
cout<<“\nSchool id=”<<s_id;
}
};

class science : virtual public teacher
{
protected:
int science_code;
float science_marks;
public:
void get_sc()
{
cout<<“\nEnter science code?”;
cin>>science_code;
cout<<“\nEnter marks in science?”;
cin>>science_marks;
}
void put_sc()
{
cout<<“\nScience code =”<<science_code;
cout<<“\nMarks in Science =”<< science_marks;
}
};

class maths : virtual public teacher
{
protected:
int maths_code;
float maths_marks;
public:
void get_mc()
{
cout<<“\nEnter code for mathematics?”;
cin>>maths_code;
cout<<“\nEnter marks in Maths?”;
cin>>maths_marks;
}
void put_mc()
{
cout<<“\nMaths code =”<<maths_code;
cout<<“\nMarks in Maths =”<<maths_marks;
}
};

class tests_conducted : public science, public maths
{
protected:
float total_marks;
public:
void compute()
{
total_marks = science_marks + maths_marks;
}
void put_info()
{
put_v();
put_sc();
put_mc();
cout<<“\nTotal Marks =”<<total_marks;
}
};

void main()
{
clrscr();
tests_conducted test;
test.get_v();
test.get_sc();
test.get_mc();
test.compute();
test.put_info();
getch();
}

 

Sorry, the comment form is closed at this time.