Member function pointers and virtual functions serve different purposes when it comes to runtime behavior modification. Here's why you might choose one over the other:
Virtual functions are best when you have a fixed set of behaviors that vary based on the type of object:
class Character {
public:
virtual void Attack() {
std::cout << "Basic attack\n";
}
};
class Warrior : public Character {
public:
void Attack() override {
std::cout << "Sword attack\n";
}
};
Member function pointers are more flexible when you need to:
Here's an example:
#include <iostream>
class Character {
public:
using AttackFunc = void (Character::*)();
void SetAttack(AttackFunc NewAttack) {
CurrentAttack = NewAttack;
}
void ExecuteAttack() {
(this->*CurrentAttack)();
}
void SlashAttack() {
std::cout << "Slash attack!\n";
}
void FireballAttack() {
std::cout << "Fireball attack!\n";
}
private:
AttackFunc CurrentAttack{
&Character::SlashAttack};
};
int main() {
Character player;
player.ExecuteAttack();
player.SetAttack(&Character::FireballAttack);
player.ExecuteAttack();
}
Slash attack!
Fireball attack!
The key differences are:
Choose virtual functions when behavior is tied to type hierarchy, and member function pointers when you need more dynamic behavior switching or configuration-based behavior selection.
Answers to questions are automatically generated and may not have been reviewed.
Learn how to create pointers to class functions and data members, and how to use them