0% found this document useful (0 votes)
9 views9 pages

Virtual Base Class in Inheritance in C++

Virtual base classes in C++ are used to prevent multiple instances of a class in an inheritance hierarchy, particularly when using multiple inheritance. They resolve ambiguity by allowing a base class to be inherited virtually, ensuring only one copy of its data members is shared among derived classes. The document provides examples illustrating the implementation and benefits of virtual base classes, including a program that demonstrates their use in a student grading system.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views9 pages

Virtual Base Class in Inheritance in C++

Virtual base classes in C++ are used to prevent multiple instances of a class in an inheritance hierarchy, particularly when using multiple inheritance. They resolve ambiguity by allowing a base class to be inherited virtually, ensuring only one copy of its data members is shared among derived classes. The document provides examples illustrating the implementation and benefits of virtual base classes, including a program that demonstrates their use in a student grading system.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 9

Virtual base class in C++

Virtual base classes are used in virtual inheritance in a way of


preventing multiple “instances” of a given class appearing in an
inheritance hierarchy when using multiple inheritances.
Need for Virtual Base Classes: Consider the situation where we have
one class A . This class A is inherited by two other classes B and C.
Both these class are inherited into another in a new class D

data members/function of class A are inherited twice to class D. One


through class B and second through class C. When any data / function
member of class A is accessed by an object of class D, ambiguity
arises as to which data/function member would be called? One
inherited through B or the other inherited through C. This confuses
compiler and it displays error.
Example: To show the need of Virtual Base Class in C++

#include <iostream>
using namespace std;

class A {
public:
void show()
{
cout << "Hello form A \
n";
}
};

class B : public A {
};

class C : public A {
};

class D : public B, public C {


};

int main()
{
D object;
object.show();
}

Compile Errors:
prog.cpp: In function 'int main()':
prog.cpp:29:9: error: request for member 'show' is
ambiguous
object.show();
^
prog.cpp:8:8: note: candidates are: void A::show()
void show()
^
prog.cpp:8:8: note: void A::show()

How to resolve this issue?


To resolve this ambiguity when class A is inherited in both class B and
class C, it is declared as virtual base class by placing a
keyword virtual as :
Syntax for Virtual Base Classes:
Syntax 1:
class B : virtual public A
{
};

Syntax 2:
class C : public virtual A
{
};
Note:
virtual can be written before or after the public. Now only one copy of
data/function member will be copied to class C and class B and
class A becomes the virtual base class. Virtual base classes offer a
way to save space and avoid ambiguities in class hierarchies that use
multiple inheritances. When a base class is specified as a virtual base,
it can act as an indirect base more than once without duplication of its
data members. A single copy of its data members is shared by all
the base classes that use virtual base.
Example 1
#include <iostream>
using namespace std;

class A {
public:
int a;
A() // constructor
{
a = 10;
}
};

class B : public virtual A {


};

class C : public virtual A {


};

class D : public B, public C {


};

int main()
{
D object; // object creation
of class d
cout << "a = " << object.a
<< endl;

return 0;
}

Output:
a = 10
Explanation :
The class A has just one data member a which is public. This class is
virtually inherited in class B and class C. Now class B and
class C becomes virtual base class and no duplication of data
member a is done.
Example 2:
#include <iostream>
using namespace std;

class A {
public:
void show()
{
cout << "Hello from A \
n";
}
};

class B : public virtual A {


};

class C : public virtual A {


};

class D : public B, public C {


};

int main()
{
D object;
object.show();
}

Output:
Hello from A
Now, in this article, you will explore the virtual base class in C++ as a
whole. Consider the case where there is just one class A. Two other
grades, B and C, descend from this class A.
The data members/functions of class A are inherited twice to class D, as
seen in the diagram. The first will take you through class B, and the
second will take you through class C. When an object of class D accesses
any data or function member of class A, it's unclear which data or function
member would be named. One was inherited via B, and it inherited the
other via C. This throws the compiler into a loop and causes an error to
appear.

Example:

#include <iostream>
using namespace std;
class A {
public:
int a;
A(){
a = 10;
}
};
class B : public virtual A {
};
class C : public virtual A {
};
class D : public B, public C {
};
int main(){
//creating class D object
D object;
cout << "a = " << object.a << endl;
return 0;
}

Output

AIM: - Create a class student having student uid and


getnumber(),putnumber() as member functions to get the values and display
it. Derive a class test having marks in different subjects and getmarks() and
putmarks() as member functions to get and display the values. Derive
another class sports from student class having sports score and getscore(),
putscore() as member functions to get and display the values. Derive a class
result from test and sports class and define a function display() to calculate
total marks. Implement it with the object of result class. If it gives any error,
resolve it by adding the required functionality.
Program Code:-

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

using namespace std;

class student {
int rno;
public:

void getnumber() {
cout << "Enter Roll No:";
cin>>rno;
}

void putnumber() {
cout << "\n\n\tRoll No:" << rno << "\n";
}
};

class test : virtual public student {


public:
int part1, part2;

void getmarks() {
cout << "Enter Marks\n";
cout << "Part1:";
cin>>part1;
cout << "Part2:";
cin>>part2;
}

void putmarks() {
cout << "\tMarks Obtained\n";
cout << "\n\tPart1:" << part1;
cout << "\n\tPart2:" << part2;
}
};

class sports : public virtual student {


public:
int score;

void getscore() {
cout << "Enter Sports Score:";
cin>>score;
}

void putscore() {
cout << "\n\tSports Score is:" << score;
}
};

class result : public test, public sports {


int total;
public:

void display() {
total = part1 + part2 + score;
putnumber();
putmarks();
putscore();
cout << "\n\tTotal Score:" << total;
}
};

int main() {
result obj;
obj.getnumber();
obj.getmarks();
obj.getscore();
obj.display();
return 0;
}

Program No. 5 (iii)

Aim: - WAP to illustrate how the constructors are implemented and the order
in which they are called when the classes are inherited. Use three classes
named alpha, beta, gamma such that alpha, beta are base class and gamma
is derived class inheriting alpha &beta. Pass four variable to gamma class
object which will further send one integer variable to alpha(),one float type
variable to beta().Show the order of execution by invoking constructor of
derived class.

Program Code:-
#include<iostream>
#include<conio.h>
using namespace std;
class alpha
{
int x;
public:
alpha(int i)
{
x=i;
cout<<"alpha initialized\n";
}
void show_x()
{
cout<<"x="<<x<<"\n";
}
};
class beta
{
float y;
public:
beta(float j)
{
y=j;
cout<<"beta initialized\n";
}
void show_y()
{
cout<<"y="<<y<<"\n";
}
};
class gamma : public beta,public alpha
{
int m,n;
public:
gamma(int a,float b,int c,int d): alpha(a),beta(b)
{
m=c,n=d;
cout<<"gamma initialized\n";
}
void show_mn()
{
cout<<"m="<<m<<"\n";
cout<<"n="<<n<<"\n";
}
};

int main()
{
gamma g(5,10.75,20,30);
g.show_x();
g.show_y();
g.show_mn();
return 0;
}

You might also like