Reputation: 49
I have a question for this scheme:
class computer_mouse
{
left_click() { };
track_wheel() { };
right_click() { };
}
class game_mouse: public computer_mouse
{
double_shot() { };
throw_grenade() { };
sit_down() { };
}
class design_mouse: public computer_mouse
{
increase_zoom() { };
decrease_zoom() { };
}
class computer
{
computer_mouse *my_mouse;
}
I want to do this:
computer_mouse *my_mouse = new game_mouse();
my_mouse->double_shot();
How can I call a descendant function from a base class?
Upvotes: 1
Views: 427
Reputation: 409136
You have to use e.g. static_cast
for that:
computer_mouse *my_mouse = new game_mouse();
static_cast<game_mouse*>(my_mouse)->double_shot();
From the above linked Wikipedia page:
The static_cast operator can be used for operations such as
- Converting a pointer of a base class to a pointer of a derived class,
Upvotes: 3
Reputation: 9579
Don't do this:
computer_mouse *my_mouse = new game_mouse();
my_mouse->double_shot();
Do this:
game_mouse *my_mouse = new game_mouse();
my_mouse->double_shot();
Upvotes: 0
Reputation: 9523
By using static_cast
:
static_cast<game_mouse*>(my_mouse)->double_shot();
However, the methods should be public, and not private!
class game_mouse: public computer_mouse
{
public:
double_shot() { };
throw_grenade() { };
sit_down() { };
}
Upvotes: 1