Write a C++ program to implement the concept of virtual base class.


Algorithm to solve the above problem:
1. Start the program
2. Include suitable header files
3. Create a base class student and sports
4. In the base class student define the function void get number and put number
5. In the base class sports define the function void get score and void put score
6. Derive a class test form base student and define the function get mark and put mark
7. Derive a class result from test and sports class and define function void display
8. Get the value for get number, get marks and get score function through main function
9. Call the display function in class result
10. Stop the program

Implementation of the above problem in C++:
#include<iostream>
using namespace std;
class student
{
protected:
int roll_number;
public:
void get_number(int a)
{
roll_number=a;
}
void put_number()
{
cout<<"ROLL NO:"<<roll_number<<"\n";
}
};
class test:public virtual student
{
protected:
int part1,part2;
public:
void get_marks(int x, int y)
{
part1=x;
part2=y;
}
void put_marks()
{
cout<<"MARKS:"<<"\n"<<"Part1="<<part1<<"\n"<<"Part2="<<part2<<"\n";
}
};
class sports: public virtual student
{
protected:
float score;
public:
void get_score(int s)
{
score=s;
}
void put_score()
{
cout<<"Sports:"<<score<<"\n\n";
}
};
class result: public test, public sports
{
int total;
public:
void display()
{

total=part1+part2+score;
put_number();
put_marks();
put_score();
cout<<"TOTAL SCORE:"<<total<<"\n";
}
};
int main()
{
result student;
student.get_number(101);
student.get_marks(60,70);
student.get_score(30);
student.display();
return 0;
}

The output of the above program is tested on www.jdoodle.com
Output:
ROLL NO:101
MARKS:
Part1=60
Part2=70
Sports:30

TOTAL SCORE:160

Thanks
Mukesh Rajput
Mukesh Rajput

Mukesh Rajput

I am a Computer Engineer, a small amount of the programming tips as it’s my hobby, I love to travel and meet people so little about travel, a fashion lover and love to eat food, I am investing a good time to keep the body fit so little about fitness also..

Post A Comment:

0 comments: