I am trying to implement a character selection method, for a text based game and i know that it will not work the way i did it, because i am returning a refernce to an object with a lifetime limited to the scope of the method call. I have also tried to implement the method without referencing the Fighter parent class and returning a child class (Samus and Ryu) based on the players character choice, but then i would get this error: invalid abstract return type 'Fighter'.
Fighter characterSelection(int player,bool checkForBot, Fighter &fig)
{
int input;
string newName;
if(checkForBot)
{
input = (rand()%2)+1;
}
else{
cout << "Please choose your Fighter player"<<player<<": \n1. Samus\n2. Ryu\n";
input = readInput<int>();
}
if(input == 1)
{
Samus sam;
if(checkForBot)
{
cout << "Bot selected Samus!";
}
else{
cout << "Player"<<player<<" selected Samus!\nDo you wish to change your fighters name?\n1.Yes\n2.No\n";
input = readInput<int>();
if(input == 1)
{
cout << "new Name: ";
newName = readInput<string>();
changeName(newName,sam);
}
}
return sam;
}
else if(input == 2)
{
Ryu ry;
if(checkForBot)
{
cout << "Bot selected Ryu!";
}
else {
cout << "Player"<<player<<" selected Ryu!\nDo you wish to change your fighters name?\n1.Yes\n2.No\n";
input = readInput<int>();
if(input == 1)
{
cout << "new Name: ";
newName = readInput<string>();
changeName(newName,ry);
}
}
return ry;
}
}
After having chosen one character and the end of the function call, the destructor of the object is called upon, thus making the reference linked to a non-existing object.
int main()
{
int input;
string newName;
bool checkForBot;
int player=1;
while(true)
{
cout << "1. PVP \n2. PVE\n";
input = readInput<int>();
if(input == 1)
{
checkForBot = false;
//Character Selection
Fighter &fig1 = characterSelection(player,checkForBot,fig1);
player++;
Fighter &fig2 = characterSelection(player,checkForBot,fig2);
//Battle
fightPVP(fig1, fig2);
}
else if(input ==2)
{
//Character Selection
Fighter &fig1 = characterSelection(player,checkForBot,fig1);
checkForBot = true;
Fighter &bot = characterSelection(player,checkForBot,bot);
//Battle
fightPVE(fig1, bot);
}
}
return 0;
}
Is there any other way i could solve this problem, instead of referencing the parent class and then creating the child in the function call?
In this:
Fighter &fig1 = characterSelection(player,checkForBot,fig1);
you are making a reference to a local object copy returned by the function.
Returning a parent object has also the issue of object slicing; you should have that in account.
If that's not a problem, however, you can add a copy constructor to the class and just remove the reference when declaring the receiving variable:
Fighter fig1 = characterSelection(player,checkForBot,fig1);
If your object is not suited to copy, other way is to new
the object in characterSelection
and return a pointer (or better, shared pointer) of the base class.