How do I access a private member of a class?

class Foo
{
public:
     int blah;
private:
     bool whatever;
};

int main()
{
Foo* myFoo;

myFoo->whatever = true;    //does not work obviously
}

How do I access 'whatever'? Thanks.

Recommended Answers

All 2 Replies

>How do I access 'whatever'?
You don't. That's the whole point of making it private. Only the class itself and friends of the class can access private members. You can allow access but still control it by offering a public interface:

class Foo {
public:
  int blah;

  void set_whatever ( bool value )
  {
    whatever = value;
  }
private:
  bool whatever;
};

int main()
{
  Foo myFoo;

  myFoo.set_whatever ( true );
}

Why in the world do you actually MAKE the member private if you INTEND to change it from elsewhere?!

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.