virtual function()

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
#include <iostream>
#include <string>

using namespace std;

class A{
private:
	string AFood;

public:

	A( string theAFood){
		AFood = theAFood;
	}
	virtual void 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;
	}

	virtual void 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;
	}

	virtual void 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

so whats my error ?
To get that output you need to call the displayFoodType function.
1
2
B2.displayFoodType();
C1.displayFoodType();
You should check that appropriate foods do begin with the correct letter.


The display I done it , sorry for didn't updated
1
2
3
4
B1.displayFoodType();
	B2.displayFoodType();
	C1.displayFoodType();
	C2.displayFoodType();


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.
cant get what u mean . so mean cn i do it?
Topic archived. No new replies allowed.