Signum Signum - 2 months ago 10
C++ Question

Compiler calling base class method instead of children one

First sorry for the code being in a foreign language.

Im having a problem, when I compile the code below the compiler calls the base method instead of the child one.

I have this base class :

Jugador.h

#ifndef JUGADOR_H_
#define JUGADOR_H_

#include <iostream>
using namespace std;

class Jugador{
protected:
bool color;//true->rojo false-> azul
public:
Jugador(bool rojo) { color = rojo; }
Jugador() {}
virtual string getInput();
~Jugador(){}
};

#endif


Jugador.cpp

#include "Jugador.h"
using namespace std;
string Jugador::getInput(){
cout<<"Is Called"<<endl;
}


And this child class:
JugadorHumano.h

#ifndef JUGADORHUMANO_H_
#define JUGADORHUMANO_H_
#include <iostream>
#include <string>
#include "Jugador.h"

using namespace std;

class JugadorHumano: public Jugador {
public:
JugadorHumano(bool rojo) :Jugador(rojo) {}
virtual string getInput();//Tested with override too
};

#endif


JugadorHumano.cpp

#include "JugadorHumano.h"
using namespace std;

string JugadorHumano::getInput(){
string input;
getline(cin, input);
return input;
}


Then, on a third class method unrelated to those two outside using them I have made:

Jugador rojo;
rojo=JugadorHumano(true);
rojo.getInput();


Thanks for your attention.

Edit: Sorry, this is my first question, added the cpp files

Edit2: Made the changes sugested by @Raindrop7 , now compiles but still calls base method, it prints "Is Called" instead of doing the getline.

Edit3:Thanks

OLD:When the compiler arrives to getInput it throws an error "Reference to 'Jugador::getInput()' is undefined". I'm not sure why this happens nor a way to fix it.

HAG HAG
Answer

If don't want to define getInput() in your base class (Jugador), as per your comments, then you need to make it pure virtual

virtual string getInput()=0;

However, you will not be able to instantiate Jugador since it will become an abstract class,

Jugador rojo; // error tries to instantiate abstract class 

Thus, in your third class you need to create JugadorHumano object

Jugador * rojo = new JugadorHumano(true);
rojo->getInput();