In the following class, i'm aware the output will be:
Func A game
Func B game
Func A game
Func B game
and to fix it would be to make the Game functionB() virtual but I was just wondering why rpg->functionB() would call the method in the Game class as opposed to the RPG class? Can anyone help?
class Game {
public: Game() {};
void functionA() {cout << "Func A game" << endl;};
void functionB() {cout << "Func B game" << endl;};
};
class RolePlayGame: public Game {
public: RolePlayGame() {};
void functionB(){ cout << "Func B role play" << endl; };
};
int main(){
Game* g = new Game; Game* rpg = new RolePlayGame;
g->functionA();
g->functionB();
rpg->functionA();
rpg->functionB();
delete g;
delete rpg;
return 0;
}
I don't see any functions declared virtual
in your code. Only virtual functions are resolved at runtime; non-virtual functions are resolved at compile time, according to the static type.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.