I'm having this weird issue with a text based RPG I'm trying to create. I'm fairly new to C++, so I thought having a project that I can work on and expand as I learn more would be a good way to put what I have been reading about into actual practice. Today I read about Constructors with arguments.
Before I read this, I had my constructor create my object Player globally, where all it's stats were set to 0. Then there is a point where you have to select between the class Warrior or Mage. Depending on which you choose, another function is called to set all your characters stats to what I wanted to be their defaults.
My book tells me this isn't the best way to do it, since I'm relying on an outside function to set the stats for me, which isn't a good idea in OO programming. So instead, I created the following constructor:
Character(int defStrength=0, int defIntelligence=0, int defAgility=0, int defDefense=0, int defHealth=0, int defLevel=0)
{
cStrength= defStrength; cIntelligence= defIntelligence; cAgility= defAgility; cDefense= defDefense;
cHealth= defHealth; cLevel= defLevel;}
It accepts defStrength, DefInt etc as arguments, and then set's the character stats to those.
for(;;){
cout<<"\n\nBefore we begin, please select your class."
<<"\nEnter a 'W' for Warrior or an 'M' for Mage. ";
char classChoice;
cin>> classChoice;
if(classChoice=='W'|| classChoice=='w'){
Character player(5, 2, 3, 3, 10, 1);
player.DisplayStats();
break;
}
if(classChoice=='M'|| classChoice=='m'){
Character player(2, 5, 3, 2, 10, 1);
player.DisplayStats();
break;
}
else{
cout<<"You did not enter a legal value.\n";
}
}
The new problem, however, is that when my object player is created within the if{ or switch() brackets, when it exits the object is destroyed. ( I added a cout to my destructor just to be sure, and it was indeed executing it) If I take out the if{ or switch() statements, the object works as it should. The only problem is if I do that, I have no idea how I am supposed to code a way to select your class.
The function displayStats() is part of my Character class, and simply couts the values of cStrength, cIntelligence, etc. When the function is called within the if{ brackets, it returns the values as it should, but as soon as it leaves, all the stats are reverted back to 0.
Also, the only way I got my code to compile is to make player global, otherwise when it encounters my first player.memberfunction(), it says first declaration.
Any help would be greatly appreciated.