Using virtual inheritance to share a common base - C++ Class

C++ examples for Class:Inheritance

Description

Using virtual inheritance to share a common base

Demo Code

#include <cstdio>
#include <cstdlib>
#include <iostream>
using namespace std;

class Furniture//from   www. j a  v a  2 s.  co m
{
  public:
    Furniture(int w) : weight(w) {}
    int weight;
};

class Bed : virtual public Furniture
{
  public:
    Bed(int w = 0) : Furniture(w) {}
    void sleep(){ cout << "Sleep" << endl; }
};

class Sofa : virtual public Furniture
{
  public:
    Sofa(int w = 0) : Furniture(w) {}
    void watchTV(){ cout << "Watch TV" << endl; }
};

class SleeperSofa : public Bed, public Sofa
{
  public:
    SleeperSofa(int w) : Furniture(w) {}
    void foldOut(){ cout << "Fold out" << endl; }
};

int main(int nNumberofArgs, char* pszArgs[])
{
    SleeperSofa ss(10);

    cout << "Weight = " << ss.weight << endl;

    return 0;
}

Result


Related Tutorials