Virtual function in c++

Hi everyone, i have an exercise using virtual function. I understand virtual function when use it with pointer. But i dont understand what this exercise want me to do.

Here it is:
-------------------------------------------------------------------------------
Some animals' speed

[Table]
-------------------
Human: 30 km/h
Leopard: 100 km/h
Lion: 70 km/h
------------------

Write a program to compare 2 animals speed, for instance, Human-Leopard, .....
Now, add horse (70 km/h) into that box, how the program changes?
-------------------------------------------------------------------------------

I know i should create a
1
2
3
4
class Animal,
 then class Human: public Animal,
class Leopard : public Animal,
and class Lion : public Animal.


Someone help! thks in advance
Virtual functions in C++ implement object methods. So to use them, you need to instantiate an object and invoke that method.

Your homework requires you to create instances of the described objects, call the method and compare the results.
SOmething like this>>??

1
2
3
4
5
6
7
8
9
class Animal
{
protected:
	float speed;
public:
	virtual float getspeed() = 0;
	
};


1
2
3
4
5
6
7
8
class Human : public Animal
{
public:
	float getspeed()
	{
		return speed = 30;
	}
};

.
.
.
.

main.cpp
1
2
3
4
5
6
7
8
Animal *p = new Human;
Animal *q = new Lion;
	if (p->getspeed() > q->getspeed()) cout << "Human faster" << endl;
	else
	if (p->getspeed() < q->getspeed())
		cout << "Lionn faster" << endl;
	else
		cout << "Equal" << endl;
Yes, that's it.

It helps if you use meaningful variable names.
so if we add Horse, nothing happen????? just add another class
I'm not sure what you mean.
"Now, add horse (70 km/h) into that box, how the program changes?"

That give me something to consider!!!!!
Topic archived. No new replies allowed.