I have been using different tutorials over the past few days to achieve this terrible terrible code and I feel I am almost at the stage where it will work the way I want it to.. Except for one thing.
I have made my class called cPlayer and I can assign the values, but when I try to access these values from my BattleFunc, it gives me an error saying undeclared identifier.
I understand there is probably some gaping hole in my knowledge of C++ programming, but for all my googling I cant find a solution to this.
cPlayer isn't a global variable, neither a BattleFunc local variable, so the compiler doesn't know where to find it. Try passing a CClass pointer as BattleFunc arguments and see what happen. If you don't know how to do it let me know. :)
Variables exist only in the scope in which they're declared. They are "invisible" outside that scope. Scope is usually defined by {curly braces}.
For example:
1 2 3 4 5 6 7 8 9 10 11
int main()
{
cout << "scope example\n";
{ // adding curly braces here just for scope
int var = 10; // var is declared inside this scope
} // var's scope ends here. IE: it no longer exists
cout << var; // ERROR, 'var' is undeclared
}
Your problem is similar, only instead of a nested scope like that example, you have it in a separate function:
1 2 3 4 5 6 7 8 9 10 11 12 13
int main()
{
CClass cPlayer; // cPlayer declared in this scope.
//...
} // <- cPlayer's scope ends here
// at this point, 'cPlayer' is no longer defined
void BattleFunc()
{
//...
if( cPlayer.whatever ... // <- ERROR, cPlayer is undeclared
Common solutions are:
1) Broaden the scope of cPlayer by defining it at a "higher level"... like globally. DON'T DO THIS, I am only mentioning it for completeness but it's a bad idea
2) Pass cPlayer to functions that need it as a function parameter. iHutch105's example illustrates how to do this.
Ok your function needs a definition of cPlayer, because it declared in main function but not in BattleFunc. So you need to give at your BattleFunc the variable that he need, ok?
You can do it in two ways, with a pointer or a reference. Let's try with a reference (how iHutch seggested you):
your function will be: void BattleFunc( const CClass &cPlayer )
so you are saying that your function needs an argument of CClass type.
when you call this function you'll do this:
BattleFunc( cPlayer );
in this way you can operate on cPlayer variable inside your BattleFunc.