Calling derived class's functions in a function with parameter of base class

Say I have 3 classes:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Player 
{
    public:
        virtual func1();
};

class Human: public Player
{
    public:
        func1(); //implementing Player's func1()
        func2(); //Human's own function
};

class Computer : public Player
{
    public:
        func1(); //implementing Player's func1()
        func3(); //Computer's own function
};


Say in my main class, I have a function fight(Player p1, Player p2) and I would like to do something like this in the fight function, given that p1 is the human and p2 is the computer:

1
2
3
4
5
6
7
//function fight()
fight(Player p1, Player p2)
{
    p1.func2();
}
//using function fight()
fight(human, computer);


When I compile the program, I got this:
error: ‘class Player’ has no member named 'func2()'

What can I do to allow p1 to call func2 inside fight()? I'm not allowed to use pointers as the parameter for fight() and have to use the signature fight(Player p1, Player p2).
As far as my knowledge goes you cannot call a derived class member function from the base class. You will have to modify the signature to fight(Human p1, Computer p2).
The compiler is right. Class Plyer has no a function with name func2.
Last edited on
Is there a way I can force the code to use Human's func2 if in fight() I had a checking to make sure p1 is human? Like a C++ grammar, syntax thing?
If you pass derived objects then you can use dynamic_cast.

Last edited on
Can you give me an example please (related to my question)? (on the dynamic_cast, I've read the tutorial on this website but it only applies to pointers). Thanks.
Last edited on
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
#include <iostream>

int main()
{
	class Player 
	{
	public:
		virtual void func1() const = 0;
	};

	class Human: public Player
	{
	public:
		void func1() const { std::cout << "I am a Human" << std::endl; }
		void func2() const { std::cout << "I will win the Game!" << std::endl; }
	};

	class Computer : public Player
	{
	public:
		void func1() const { std::cout << "I am a Computer" << std::endl; }
		void func2() const { std::cout << "No, it is me, computer, who will win the Game!" << std::endl; }
	};

	class Game
	{
	public:
		static void fight( const Player &p1, const Player &p2 )
		{
			p1.func1();
			p1.func1();

			dynamic_cast<const Human &>( p1 ).func2();
			dynamic_cast<const Computer &>( p2 ).func2();
		}
	};

	Human human;
	Computer computer;

	Game::fight( human, computer );

	return 0;
}
Topic archived. No new replies allowed.