Please note, this is a STATIC archive of website www.tutorialspoint.com from 11 May 2019, cach3.com does not collect or store any user information, there is no "phishing" involved.
Tutorialspoint

C++ example to implement virtual inheritance

#include <iostream>

using namespace std;

class Person {
public:
    Person()
    {
        cout << "Default Constructor of Person() " << endl;
    }
    Person(int x)
    {
        cout << "In Person:" << x << endl;
    }
};
class Faculty : virtual public Person {
public:
    Faculty(int x)
        : Person(x)
    {
        cout << "In Faculty:" << x << endl;
    }
};
class Student : virtual public Person {
public:
    Student(int x)
        : Person(x)
    {
        cout << "In Student:" << x << endl;
    }
};
class TA : public Faculty, public Student {
public:
    TA(int x)
        : Student(x)
        , Faculty(x)
    {
        cout << "In TA:" << x << endl;
    }
};

class A {
    int x;

public:
    /*void setX(int i)
    {
        x=i;
    }*/
    A()
    {
        cout << "Default fo A" << endl;
    }
    A(int i)
    {
        x = i;
    }
    void print()
    {
        cout << "A:" << x << endl;
    }
};
class B : virtual public A {
public:
    B()
        : A(10)
    {
        //setX(60);
    }
};
class C : virtual public A {
public:
    C()
        : A(10)
    {
        // setX(80);
    }
};
class D : public B, public C {
public:
    D()
        : B()
        , C()
        , A(10)
    {
    }
};

int main()
{
    // TA ta1(30);
    D d;
    d.print();
    return 0;
}

Advertisements
Loading...

We use cookies to provide and improve our services. By using our site, you consent to our Cookies Policy.