(7 pts) Question S: Classes with Inheritance and the Diamond Problem in this pro
ID: 3743827 • Letter: #
Question
(7 pts) Question S: Classes with Inheritance and the Diamond Problem in this problem, different kinds of bats forage for food. Objects in class A are fruiteaters and will eat fruit. Possible food items are found at random using the method find food0 string Find foodO only Not Shown:The tostream is included and we are using the std nanespace nt n-HIDDEN a random int , 1 or 2 string food-("fruit"- "blood, .decaying matter") returm foodn); Class A are the fruiteaters class A f public: boot eat(string food)t if (foodFruit" coutExplanation / Answer
#include<iostream>
#include<string>
#include<cstdlib>
using namespace std;
string find_food(){
int n = rand() % 3 ; // random number 0,1 or 2
string food[] = {"fruit","blood","decaying matter"};
return food[n];
}
class A{
public: bool eat(string food){
if(food == "fruit"){
cout<<"I'm a fruiteater and I'm eating some fruit!"<<endl;
return true;
}
else{
cout<<"Yuk! Fruiteaters don't eat "<<food<<endl;
return false;
}
}
};
class B:public A{
public: bool eat(string food){
if(food == "blood"){
cout<<"I'm a bloodsucker and I'm eating some blood!"<<endl;
return true;
}
else{
cout<<"Yuk! Bloodsuckers don't eat "<<food<<endl;
return false;
}
}
};
class C:public A{
};
class D:public B,public C{
public: bool eat(string food){
if(food == "blood" || food == "fruit"){
cout<<"I'm an omnivore and I'm eating some "<<food<<"!"<<endl;
return true;
}
else{
cout<<"Yuk! Even omnivore don't eat "<<food<<endl;
return false;
}
}
};
int main(){
A a;
cout<<" Object a in A: "<<endl;
bool foundfood = false;
string food = find_food();
foundfood = a.eat(food);
while(!foundfood){
food = find_food();
foundfood = a.eat(food);
}
B b;
cout<<" Object b in B: "<<endl;
foundfood = false;
while(!foundfood){
food = find_food();
foundfood = b.eat(food);
}
C c;
cout<<" Object c in C: "<<endl;
foundfood = false;
while(!foundfood){
food = find_food();
foundfood = c.eat(food);
}
D d;
cout<<" Object d in D: "<<endl;
foundfood = false;
while(!foundfood){
food = find_food();
foundfood = d.eat(food);
}
return 0;
}//end of program
//output (out may be differ as using random number in find_food())
Object a in A:
Yuk! Fruiteaters don't eat blood
Yuk! Fruiteaters don't eat blood
I'm a fruiteater and I'm eating some fruit!
Object b in B:
I'm a bloodsucker and I'm eating some blood!
Object c in C:
Yuk! Fruiteaters don't eat decaying matter
Yuk! Fruiteaters don't eat blood
Yuk! Fruiteaters don't eat blood
I'm a fruiteater and I'm eating some fruit!
Object d in D:
I'm an omnivore and I'm eating some fruit!
Question 7:
if class D dont have eat method for avoiding the diamond problem can use resolution operator
like if want to use eat method from B then can write B::eat and for class C C::eat
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.