#include <iostream>
#include <string>
usingnamespace std;
class A{
private:
string AFood;
public:
A( string theAFood){
AFood = theAFood;
}
virtualvoid displayFoodType() const{
}
virtual string getAFood() const {
return AFood;
}
};
class B : public A{
private:
string BFood;
public:
B( string theBFood , string theAFood ) : A( theAFood ){
BFood = theBFood;
}
virtual string getBFood() const{
return BFood;
}
virtualvoid displayFoodType() const{
cout << "---------------------\nA is for " << getAFood() << "\nB is for " << getBFood() << endl;
}
};
class C : public B{
private:
string CFood;
public:
C( string theCFood , string theBFood , string theAFood ) : B( theBFood , theAFood ){
CFood = theCFood;
}
virtual string getCFood() const {
return CFood;
}
virtualvoid displayFoodType() const{
cout << "---------------------\nA is for " << getAFood() << "\nB is for " << getBFood() << "\nC is for " << getCFood() << endl;
}
};
int main(){
B B1( "Burger" , "Avocado" );
B B2( "Bean " , "Acorn" );
C C1( "Cheese" , "Blueberry" , "Almond" );
C C2( "Cherry" , "Banana" , "Apple" );
cin.get();
return 0;
}
Output should be :
1 2 3 4 5 6
A is for Acorn
B is for Bean
---------------------
A is for Almond
B is for Blueberry
C is for Cheese
How should i implement it to using the virtual function? tried it but keep fail , because yesterday only learn , hard to get it , pass by constructor i think mine is correct already
but now i have to declare a function that if my instance object , that for AFood is not start with letter 'A' or 'a' , the constructor won't pass it , same to BFood and CFood , BFood must start with case 'b' or 'B' if not it won't pass to constructor and wont out the statement
example i insert
C C1( "Cheese" , "Clueberry" , "Diamond" );
so the output will be:
C is for Cheese
B and A won't come out since it's not begin with the letter b and a
Declaring a function virtual only makes a difference if you access it through a pointer or a reference to the object. In your case, you're accessing your objects directly, so it doesn't matter whether or not the functions are virtual.