Accessing private members of a class from another class

You have multiple possibilities to access members of other classes.

If a member is private (as in your case) you can either declare other classes as a friend of this class or write getters and setters.

Method 1: Getters and Setters

class A {
private: 
  int a;
public:
  int GetA() { return a; }
  void SetA(int newA) { a = newA; }
};

This however will grant access to your private data from every other place in your code. Though you can leave setA away causing only read access to the private a.


Edit:

As @tobi303 has correctly pointed out: Returning a raw pointer via a getter (as it would be in your case) is probably not a good idea. So I would recommend in this case to either return the object the pointer points to or use smart pointers like std::shared_ptr and return them:

class {
private:
  int *a;
  std::shared_ptr<int> b;
public:
  int getA() { return a ? *a : 0; } // only dereference the pointer if it points somewhere
  std::shared_ptr<const int> getB() { return b; } // return as std::shared_ptr<const int> to prevent indirect write access to a
};

Method 2: Friend Classes

class B
{};

class A {
private: 
  int a;
public: 
  friend class B;
};

In this case only B and A can access the private data of A. You can also grant access to the private data to only a few functions.

However, granting write access to private members often indicates a flaw in your design. Maybe they should be public (see Method 3) or you don’t even need write access and just reading them would be completely sufficient for your needs.

Method 3: Public Members

class A {
public:
  int a;
};

Similar to Method 1 (with both the getter and the setter) you are now granting read and write access to As member a.

If you really need read and write access to a private member, Method 2 is the way to go. But as I’ve said: Think about your design once again, do you really need this?

Leave a Comment