Reputation: 25
Im completely new to C++ and im trying to make a very simple text based combat system, but I keep getting the error: "objPlayer was not declared in this scope".
All the code is written before the main() function:
#include <iostream>
using namespace std;
//DECLARE THE UNIT CLASS
class generalUnit {
public:
int health; //the amount of health the unit has
};
//DECLARE THE PLAYER THOUGH THE UNIT CLASS
void generatePlayer() {
generalUnit objPlayer;
int objPlayer.health = 100;
}
//DECLARE AND INITIALIZE ALL COMMANDS
//CHECK STATS
void comCheckStats() {
cout << objPlayer.health << endl;
}
Upvotes: 0
Views: 2135
Reputation: 2115
You don't have to create a variable inside a class pointing to the object of that class you are using. It is already declared and is called this
.
With operator ->
you can then access member variables from this
. Like so:
#include <iostream>
#include <string>
using namespace std;
class Player
{
public:
int health;
// this is constructor
Player(int health_at_start)
{
this->health = health_at_start;
}
void comCheckStats()
{
cout << this->health << '\n';
}
};
int main()
{
// create player with 100 health
Player p1(100);
p1.comCheckStats();
// create player with 200 health
Player p2(200);
p2.comCheckStats();
}
As you can see, I am using something called constructor
to create new instance of Player. It is just function without return type, declared with the same name as the class. It initializes member variable starting data and you can pass some values to it too.
Upvotes: 1