Write C++ programs that illustrate how the following forms of inheritance are supported:
a)Single inheritance
b)Multiple inheritances
c)Multi-level inheritance
d)Hierarchical inheritance
a)
#include <iostream>
#include <string>
using namespace std;
class Grandfather{
protected:
string surname;
public:
Grandfather(string s):surname(s){}
};
class Father:public Grandfather{
string name;
public:
Father(string a, string b): Grandfather(b), name{a}{}
void details(){
cout<<name<<" "<<surname;
}
};
int main(){
Father f("Lucas", "Graham");
f.details();
return 0;
}
b)
#include <iostream>
#include <string>
using namespace std;
class Father{
protected:
string gene = "Y";
public:
Father(){}
};
class Mother{
protected:
string gene = "X";
public:
Mother(){}
};
class Son:public Father, public Mother{
public:
string genes = Mother::gene + Father::gene;
Son(){}
};
int main(){
Son son;
cout<<son.genes;
return 0;
}
c)
#include <iostream>
#include <string>
using namespace std;
class Grandfather{
protected:
string surname;
public:
Grandfather(string s):surname(s){}
};
class Father:public Grandfather{
string name;
public:
Father(string a, string b): Grandfather(b), name{a}{}
};
class Grandson: public Father{
string name;
public:
Grandson(string a, string b): Father("", b), name(a){}
void details(){
cout<<name<<" "<<surname;
}
};
int main(){
Grandson s("Lucious", "Graham");
s.details();
return 0;
}
d)
#include <iostream>
#include <string>
using namespace std;
class Father{
protected:
string ygene = "Y";
string xgene = "X";
public:
Father(){}
};
class Mother{
protected:
string gene = "X";
public:
Mother(){}
};
class Daughter:public Father, public Mother{
public:
string genes = Mother::gene + Father::xgene;
Daughter(){}
};
class Son:public Father, public Mother{
public:
string genes = Mother::gene + Father::ygene;
Son(){}
};
int main(){
Son son;
Daughter daughter;
cout<<son.genes;
cout<<endl<<daughter.genes;
return 0;
}
Comments
Leave a comment