Simple Program for Virtual Base Class Using C++ Programming

Aim

To calculate the total mark of a student using the concept of virtual base class.

Simple Program for Virtual  Base Class Algorithm/Steps:

  • Step 1: Start the program.
  • Step 2: Declare the base class student.
  • Step 3: Declare and define the functions getnumber() and putnumber().
  • Step 4: Create the derived class test virtually derived from the base class student.
  • Step 5: Declare and define the function getmarks() and putmarks().
  • Step 6: Create the derived class sports virtually derived from the base class student.          
  • Step 7: Declare and define the function getscore() and putscore().
  • Step 8: Create the derived class result derived from the class test and sports.
  • Step 9: Declare and define the function display() to calculate the total.
  • Step 10: Create the derived class object obj.
  • Step 11: Call the function get number(),getmarks(),getscore() and display().
  • Step 12: Stop the program.

Simple Program for Virtual  Base Class Example Program

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

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;
    }
};

void main() {
    result obj;
    clrscr();
    obj.getnumber();
    obj.getmarks();
    obj.getscore();
    obj.display();
    getch();
}

Sample Output

Enter Roll No: 200

Enter Marks

Part1: 90
Part2: 80
Enter Sports Score: 80


Roll No: 200
Marks Obtained
Part1: 90
Part2: 80
Sports Score is: 80
Total Score is: 250