I am a beginner at this so please bear with me. It might be something really simple that I may have missed as well. Here's the code.
class USA { // USA CLASS
public:
int Economy = 1000000000;
};
void ChooseAttributes() { // THIS FUNCTION IS CALLED SOMEWHERE IN THE CODE
if (PlayerCountryName == "USA") { // CHECK IF THE PLAYER HAS CHOSEN USA AS THEIR COUNTRY
class Player : public USA {}; // THEN INHERIT A NEW CLASS Player FROM CLASS USA
}
Player myPlayer; // MAKE AN INSTANCE OF THE CLASS Player NAMED myPlayer ;
cout << myPlayer.Economy // Print out the member ECONOMY of the object.
}
The problem arises when I make the instance of the class. It says that identifier Player is not defined meaning the class is not defined, right? But when I do this inside the IF statement, the instance IS created and I am able to access the members from the inherited class. I am using VSCODE 2019, and hovering the mouse over it says that the identifier is LOCAL. How do I make a global instance of the class?
Thank you for your time.
You appear to have a type model in mind that's more like Python. C++ is a different language. Importantly, it's compiled.
For types, that means they are entirely created at compile time, before the first if
statement is even run. At compile time, the relevant part is the { }
block. It doesn't matter whether that's if(...) {}
, while(...){}
or just plain {}
, in all cases {}
creates a block where the names inside are local to that block. Inside the block, the compiler will look outside to surrounding blocks, but the compiler will not look the other way.
This also means that in a for(...){ }
loop, you can define a type, and that type is still defined only once. You can also define a variable inside a for-loop, but that variable will be initialized every time. Variable initialization happens at runtime, type definitions happen at compile time.