C++ Question with classes [SOLVED]
Posted: Sat Aug 06, 2011 10:04 pm
Hello, I've been working on learning C++ and have been making my own small projects recently. I'm currently trying to make a small text based RPG using C++. In the process, I've been trying to use multiple files and classes for experience. So far, I've been doing things such as making a player file holding a class that contains all of the player's variables. Such as health,
playerLevel, gold, etc. I'd later make separate files that contain the game play for specific levels in the game. Such as a level1.h/level1.cpp. In the process, I've included the player file into the level1.cpp in order to get the players gold/level for reasons such as shops or combat. But whenever I try to make an object of the player class, such as "player p;" and try and, for an example, display the player's health "cout << p.health;" the value is completely different from what it is initialized to. My question is to what is causing this problem and how I can stop this from happening in the future.
Here is a quick example to make my situation more clear.
Main.cpp:
Example1.h:
Example1.cpp:
Example2.h:
Example2.cpp:
playerLevel, gold, etc. I'd later make separate files that contain the game play for specific levels in the game. Such as a level1.h/level1.cpp. In the process, I've included the player file into the level1.cpp in order to get the players gold/level for reasons such as shops or combat. But whenever I try to make an object of the player class, such as "player p;" and try and, for an example, display the player's health "cout << p.health;" the value is completely different from what it is initialized to. My question is to what is causing this problem and how I can stop this from happening in the future.
Here is a quick example to make my situation more clear.
Main.cpp:
Code: Select all
#include <iostream>
#include "example1.h"
#include "example2.h"
using namespace std;
int main(){
example1 ex1;
example2 ex2;
ex1.initVariables();
ex2.startLevel();
}
Code: Select all
#include <iostream>
using namespace std;
class example1{
public:
void initVariables();
int playerHealth, playerGold;
};
Code: Select all
#include <iostream>
#include "example1.h"
using namespace std;
void example1::initvariables(){
playerHealth = 100;
playerGold = 100;
}
Code: Select all
#include <iostream>
using namespace std;
class example2{
public:
void startLevel;
};
Code: Select all
#include <iostream>
#include "example2.h"
#include "example1.h"
using namespace std;
void example2::startLevel(){
example1 ex1;
cout << "Your Health: " << ex1.playerHealth; //When displayed, this is NOT 100 (what it was initialized to)
cout << "Your Finances: " << ex1.playerGold << " gold"; //Not what it was initialized too, either.
}