So I have been trying to split my code into several files and using headers to declare the classes and then define them in a source file. The problem is in the Source file I can access all the public functions and define them nicely, but I am not able to use the private variables inside those functions. How can you solve this?
#ifndef _PLAYER_H
#define _PLAYER_H
class Player
{
public:
void set_health(int amount); // Public set function
int get_health(); // Public get function
private:
int health;
};
#endif
#include "Player.h"
// MY PLAYER CLASS
// define our set function
void set_health(int amount)
{
health = amount;
}
// define our get function
int get_health()
{
return health;
}
#include "Player.h"
// MY PLAYER CLASS
// define our set function
void Player::set_health(int amount)
{
health = amount;
}
// define our get function
int Player::get_health()
{
return health;
}
coz these functions are members of the Player class, if you just write int get_health() that means you declare a new function, not just implementing the declared function
Also it's worth noting that because you're only using basic fuctions that returns a value, it might be easier for clarity and code consumption sake to use inline functions.
Ye that code was only a simple sample to get the grasp on classes. Easier to learn in small scale and then apply it to bigger projects once you get the concept
you cant access private variables or functions directly, you must use a function to get them, and the function cant be initialized when an instance is initialized.
class test{
private://this private line is unnecessary since classes have private initializations by default
int health; //Private health variable
public:
int get_health(void);
void set_health(int newval);
};
int test::get_health(void){
return test::health;
}
void test::set_health(int newval){
test::health = newval;
}
#include<iostream>
using namespace std;
int main(){
test Player; //create instance of test called 'Player'
Player.set_health(500); //give him 500 health
cout << Player.get_health() << endl;
system("PAUSE");
return 0;
}