|
| 1 | +#include<iostream> |
| 2 | + |
| 3 | +using namespace std;//std namespace is assigned as global namesapace |
| 4 | + |
| 5 | +//SOLVING DIAMOND PROBLEM using VIRTUAL INHERITENCE |
| 6 | + |
| 7 | + |
| 8 | +class Animal{ |
| 9 | + public: |
| 10 | + Animal() { |
| 11 | + cout<<"Animal constructor called"<<endl; |
| 12 | + } |
| 13 | + void getAnimal() { |
| 14 | + cout<<"hello I am animal"<<endl; |
| 15 | + } |
| 16 | +}; |
| 17 | + |
| 18 | +class Tiger : virtual public Animal{ |
| 19 | + public: |
| 20 | + Tiger() { |
| 21 | + cout<<"Tiger constructor called"<<endl; |
| 22 | + } |
| 23 | +}; |
| 24 | + |
| 25 | + |
| 26 | +class Lion : virtual public Animal{ |
| 27 | + public: |
| 28 | + Lion() { |
| 29 | + cout<<"Lion constructor called"<<endl; |
| 30 | + } |
| 31 | +}; |
| 32 | + |
| 33 | + |
| 34 | +class Liger: public Tiger, public Lion { |
| 35 | + public: |
| 36 | + Liger() { |
| 37 | + cout<<"Liger constructor called"<<endl; |
| 38 | + } |
| 39 | +}; |
| 40 | + |
| 41 | + |
| 42 | +int main() { |
| 43 | + Liger l; |
| 44 | + l.getAnimal(); //error if virtual inheritence is not used-'getAnimal' is ambiguous, as compiler will not know from which instance of Tiger or Lion will be used to call |
| 45 | + //getAnimal() of Animal class |
| 46 | + |
| 47 | + // when virtual inheritence is not used- |
| 48 | + //1)ANIMAL constructor called using Tiger's object2) TIGER Constructor called 3)Again Animal constructor called using LION's object |
| 49 | + //4)Lion constructor called 5)Liger constructor called at last |
| 50 | +//this happens because Liger class inherits from both Tiger and Lion class, so compiler will use the instances(objects) of both Tiger and Lion to call constructor of Animal |
| 51 | + |
| 52 | + |
| 53 | + //------------when Virtual inheritence is used----------------------- |
| 54 | + //1) Animal constructor called |
| 55 | + //2)Tiger constructor called |
| 56 | + //3) Lion constructor called |
| 57 | + //4) Liger constructor called |
| 58 | + |
| 59 | +//This happens because compiler creates only one instance(object) of Tiger or Lion class and uses it to call constructor of Animal, 2 instances of Tiger and Lion are not created |
| 60 | +//when using virtual inheritence |
| 61 | + |
| 62 | + return 0; |
| 63 | +} |
0 commit comments