Hi all,
I am having trouble in finding out how to point to a private member variable. E.g. :

#include <iostream>
using namespace std;

class Angry_Dude
{
private:
int health;
int attack;
}

I want to point to the address of health.

I know about the homework policy, and I assure you this is not any homework of any kind! Just a beginner trying to battle through the forests of programming.

Thanks in advance.

Recommended Answers

All 3 Replies

Just out of curiosity, why are you trying to circumvent the access mechanism? Those members are private for a reason, and if you need to access them from outside of the class without a field, something isn't right.

However, if you really want to use a pointer to a member, have a public member function return that pointer:

#include <iostream>

class Angry_Dude
{
private:
    int health;
    int attack;
public:
    typedef int Angry_Dude::*health_ptr_t;

    health_ptr_t health_ptr() const
    {
        return &Angry_Dude::health;
    }
};

int main()
{
    Angry_Dude ad;
    Angry_Dude::health_ptr_t p = ad.health_ptr();

    ad.*p = 12345;
    std::cout<< ad.*p <<'\n';
}

I don't recommend this method because it's both obscure and questionable class design. You'd be better off re-evaluating your class interface to account for the apparent need to have unrestricted access to private members.

I'm just looking to change health, I want to move to SDL but doesn't look like that will happen until I fully understand pointers.

Basically I want to change the value of health, I know that health is private because this is the point of Object Oriented Programming.

I'm just looking to change health, I want to move to SDL but doesn't look like that will happen until I fully understand pointers.

Basically I want to change the value of health, I know that health is private because this is the point of Object Oriented Programming.

Go with the tried and true set and get methods for your private variables:

void Angry_Dude::sethealth (int hlth)
{
    health = hlth;
}

int Angry_Dude::gethealth ()
{
    return health;
}

Both these functions should be public class functions.

commented: COOL! +1
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.