A simple application example of virtual base class

When there is a common base class on multiple inheritance paths, at the confluence of several paths, the common base class will generate multiple instances (or copies). If you want to save only one instance of the base class, you can describe the common base class as a virtual base class.

The reason for the ambiguity in inheritance may be that the inheritance class inherits the base class many times, resulting in multiple copies, that is, more than once, multiple copies of the base class members are created in memory through multiple path inheritance classes. The basic principle of a virtual base class is that there is only one copy of its members in memory. In this way, by declaring the base class inheritance as virtual, only one copy of the base class can be inherited, thus eliminating ambiguity. Use the virtual qualifier to describe the base class inheritance as virtual.

#include<iostream>
#include<string.h>
using namespace std;

class Person
{
public:
    Person(string nam, char s, int a)
    {
        name = nam;
        sex = s;
        age = a;
    }
protected:
    string name;
    char sex;
    int age;
};

class Teacher:virtual public Person
{
public:
    Teacher(string nam, char s, int a, string t):Person(nam, s, a)
    {
       title = t;
    }

protected:
    string title;
};

class Student:virtual public Person
{
public:
    Student(string nam, char s, int a, float sco):Person(nam, s, a), score(sco){}


protected:

    float score;
};

class Graduate:public Teacher, public Student
{
public:
    Graduate(string nam, char s, int a, string t, float sco, float w):
       Person(nam, s, a), Teacher(nam, s, a, t),Student(nam, s, a, sco), wage(w) {}
    void show()
    {
        cout << "name:" << name << endl;
        cout << "age:" << age << endl;
        cout << "title:" << title << endl;
        cout << "sex:" << sex << endl;
        cout << "score:" << score << endl;
        cout << "wage:" << score << endl;
    }
private:
    float wage;
};

int main(void)
{
    Graduate grad1("Wang_li", 'f', 24, "assistant", 89.5, 2400);
    grad1.show();
    return 0;
}

 

Added by tim_ver on Sat, 23 Nov 2019 17:40:14 +0200