Adding Virtual Inheritance, in multiple inheritance - C++ Class

C++ examples for Class:Inheritance

Description

Adding Virtual Inheritance, in multiple inheritance

Demo Code

#include <cstdio>
#include <cstdlib>
#include <iostream>
#define TRYIT false
using namespace std;

class Furniture {
public://  w  w  w . j a va2s. co m
  Furniture(int w) : weight(w) {}
  int weight;
};

class Bed : public Furniture
{
public:
  Bed(int weight) : Furniture(weight) {}
  void sleep() {
    cout << "Sleep" << endl;
  }
};

class Sofa : public Furniture
{
public:
  Sofa(int weight) : Furniture(weight) {}
  void watchTV() {
    cout << "Watch TV" << endl;
  }
};

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

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

  //cout << "Weight = " << ss.weight << endl; //ambiguous access

  SleeperSofa* pSS = &ss;
  Sofa* pSofa = (Sofa*)pSS;
  Furniture* pFurniture = (Furniture*)pSofa;
  cout << "Weight = " << pFurniture->weight << endl;

  return 0;
}

Result


Related Tutorials