I have an abstract class Player and its children AI and Human. In my main, when I create two objects Human and AI it works fine. But once I use them as parameters in a function that is waiting for Player pointer type, then their type is no longer AI and Human but both are Player objects.

Game.hpp :

#include "Player.hpp"
#include "Human.hpp"

class Game {
    Player *j1, *j2;

    Game(Player*, Player*);
    void setP1(Player*);
    void setP2(Player*);
    Player* getP1();
    Player* getP2();

Game.cpp :

 #include "Game.hpp"



Game::Game(Player *pp1, Player *pp2){
p1 = pp1;
p2 = pp2;

void Game::setP1(Player *pp1){
p1 = pp1;

void Game::setP2(Player *pp2){
p2 = pp2;

Player* Game::getP1(){
return p1;

Player* Game::getP2(){
return p2;

Player.hpp :

#ifndef PLAYER_H
#define PLAYER_H
#include <string>

using std::string;

class Player {
    string nom;
    int age;

    Player(string, int);
    void setNom(string);
    void setAge(int);
    string getNom();
    int getAge();

    virtual void upAge() = 0;


Here is the main.cpp :

#include "Player.hpp"
#include "Human.hpp"
#include "Game.hpp"

#include <iostream>
#include <string>

using std::cout;
using std::endl;
using std::string;

int main(){
Player *j;
Human h;
Game Game;

cout << typeid(h).name() << endl;
cout << typeid(Game.getJ1()).name() << endl;

return 0;

I would like the two cout to display the same result. But the first displays Human, and the second displays Player. How can I handle this ?

EDIT 1 : added Player.hpp file.

1 Answers

nayab On

Base class Player must contain a virtual function to get the type name as derived class.

check typeid below example from cpp reference.

#include <iostream>
#include <string>
#include <typeinfo>

struct Base {}; // non-polymorphic
struct Derived : Base {};

struct Base2 { virtual void foo() {} }; // polymorphic
struct Derived2 : Base2 {};

int main() {

    // Non-polymorphic lvalue is a static type
    Derived d1;
    Base& b1 = d1;
    std::cout << "reference to non-polymorphic base: " << typeid(b1).name() << '\n';

    Derived2 d2;
    Base2& b2 = d2;
    std::cout << "reference to polymorphic base: " << typeid(b2).name() << '\n';

Possible output:

reference to non-polymorphic base: 4Base
reference to polymorphic base: 8Derived2