Here's your code, fixed up a bit:
#include <iostream>
#include <string> // Include what you use
class player {
private:
std::string name;
int health;
int xp;
public:
void names(std::string get_name, int get_health, int get_xp) {
name = get_name;
health = get_health;
xp = get_xp;
}
// Simplest fix: Getters
std::string get_name() const { return name; }
int get_health() const { return health; }
int get_xp() const { return xp; }
};
int main() {
player p;
p.names("Mohit", 100, 3);
// cout<<p.health<<endl; // Not "within the class"
// cout<<p.xp<<endl; // Not "within the class"
// cout<<p.name<<endl; // Not "within the class"
std::cout << p.get_health() << '\n'
<< p.get_xp() << '\n'
<< p.get_name() << '\n';
player *hero = new player();
hero->names("Tavishi", 1000, 3);
std::cout << hero->get_name() << '\n'; // Prefer arrow operator over (*).
std::cout << hero->get_xp() << '\n';
std::cout << hero->get_health() << '\n';
delete hero;
return 0;
}
You were using an object in the main()
function, which is not "within the class" to attempt to access private members. When people say that you can use private members directly "within the class" they mean from within a class member function. Anything else is considered "out of the class" and the private/public restrictions are enforced.
If you need access to them, you can provide getter functions in your class, which is what I did.
Here's your code again, this time better utilizing C++. Namely, constructors and operator overloading.
#include <iostream>
#include <memory>
#include <string> // Include what you use
class player {
private:
std::string name{}; // Default member initialization makes default ctor
int health = 0; // easy to implement
int xp = 0;
public:
// Provide constructors for easier initialization
player() = default;
player(std::string name, int health, int xp)
: name(name), health(health), xp(xp) {}
// void names(std::string get_name, int get_health, int get_xp) {
// name = get_name;
// health = get_health;
// xp = get_xp;
// }
// Simplest fix: Getters
// ** Getter may not be necessary anymore if your only purpose is printing
std::string get_name() const { return name; }
int get_health() const { return health; }
int get_xp() const { return xp; }
// If you want to cout object directly, provide operator<<()
// Friends can access private members directly; they are **not** class members
friend std::ostream& operator<<(std::ostream& sout, const player& p) {
return sout << p.health << '\n' << p.xp << '\n' << p.name << '\n';
}
};
int main() {
player p{"Mohit", 100, 3}; // Much simpler initialization
// cout<<p.health<<endl; // Not "within the class"
// cout<<p.xp<<endl; // Not "within the class"
// cout<<p.name<<endl; // Not "within the class"
std::cout << p; // Simpler way to print
auto hero =
std::make_unique<player>("Tavishi", 1000, 3); // Smart pointer
// no need to delete
std::cout << *hero;
return 0;
}