I am attempting to learn C++ (currently only know PHP and some C#) and have run into my first issue.
I am trying to call a class inside a switch, then use that defined variable after the switch. However, I get the error described in the title.
#include <iostream>
#include <string>
using namespace std;
class Hero {
protected:
int hHealth,hStamina,hExp;
string hName;
public:
void Create(string);
string GetName() {
return this->hName;
}
};
class Wizard:public Hero {
public:
void SetStats(string hName) {
this->hName = hName;
this->hHealth = 40;
this->hStamina = 80;
}
};
int main() {
string hName;
int hClass;
cout << "Welcome to Ryan's Dungeons & Dragons Adventure!\n\n";
cout << "Enter your Heroes name\n";
cout << "Name: ";
cin >> hName;
cout << hName << ", please select your class\n";
cout << "(1) The Wizard\n";
cout << "(2) The Warrior\n";
cout << "(3) The Rogue\n";
cout << "(4) The Priest\n";
cout << "Class: ";
cin >> hClass;
switch (hClass) {
case 1:
Wizard _hero;
break;
}
cout << _hero->GetName();
system("PAUSE");
return 0;
}
The error in question occurs on the line:
cout << _hero->getName();
where it says _hero is undefind.
_hero
is defined only within the scope of that switch
statement. You need to create objects in the same or higher up scope that you'll be using them.
One way you can get around this is define a pointer to Hero before the switch
(initializing to null
) and then set it to a value inside the switch
. For instance:
Wizard *_hero = NULL;
switch (hClass) {
case 1:
_hero = new Wizard();
break;
}
}
if (_hero) {
cout << _hero->GetName();
}
You're also using the ->
on a class value (as opposed to a pointer to one). Scope issues aside, you probably intended to write _hero.GetName()
. Inside your class, ->
is right however since this
is a pointer to your object.