Sunday, June 11, 2017

Multiple Inheritance

/*This code was written by A. El-Gadi of Tripoli University for educational purposes. It shows one important use of multiple inheritance. For any questions  and discussion use the comment section below.*/
 
#include <iostream>

using namespace std;

class Food{};
class Wild{};


class Bird{ public: double eggsize;
            virtual void sound(){cout<<"Sound";}//It is essential to have a virtual function here for dynamic_cast<> to work.
};

class Chicken:public Bird, public Food{};
class Parrot:public Bird, public Wild{};
class Pheasant:public Bird, public Wild, public Food{};   





int main(){
const int BN(6);
Bird *b1[BN];

b1[0]=new Parrot();
b1[1]=new Chicken();
b1[2]=new Chicken();
b1[3]=new Pheasant();
b1[4]=new Parrot();
b1[5]=new Pheasant();

for(int i=0; i<BN; i++){if(dynamic_cast<Food*>(b1[i])!=NULL){cout<<i<<" is edible."<<endl;}}
for(int i=0; i<BN; i++){if(dynamic_cast<Wild*>(b1[i])!=NULL){cout<<i<<" is wild."<<endl;}}

for(int i=0; i<BN; i++){delete b1[i];}
return 0;}

No comments:

Post a Comment