3

My question is somewhat similar to the title of friend class with limited access. But the limited access I define by 'access-only'. I mean, I've a main class which does the work and creating a helper class which is useful for displaying the internals for debugging purposes. So, inside Main I defined Helper as friend.

Now I want the Helper class to just have read only access to private variables and not write access. Is it possible?

class Main {
 private:
  // DSs that I don't want to expose it to rest
  // even through getters and setters.
  DataStrcuture ds_;

  // I want a way to specify that no modifications should be
  // allowed through this helper.
  friend class Helper;
}

Now I have my helper class.

class Helper {
  Helper(Main *main) : main_(main) {
  }

  void ShowStatsAndDebugInfo() const {
    PrettyPrint(main_->ds_);
  }

 private:
  // I want this to always be used like a const variable.
  Main *main_;
}
vpshastry
  • 81
  • 1
  • 7
  • See [this](https://stackoverflow.com/questions/5424042/class-variables-public-access-read-only-but-private-access-read-write), it's a similar problem – robinsax Dec 22 '18 at 01:13
  • Yes. Pass your class Main object to the Helper by const pointer or reference. – 273K Dec 22 '18 at 01:14
  • Limiting access is rarely hard. Show us the code to get proper helpful examples. – Ted Lyngmo Dec 22 '18 at 01:39
  • Without seeing more code I'm inclined to saying that you need separation of concerns. – Ted Lyngmo Dec 22 '18 at 02:24
  • @TedLyngmo didn't get you – vpshastry Dec 22 '18 at 02:40
  • 1
    You are mixing concerns (probably). Who does what? Get that in order and it'll usually be easy to fix the rest. – Ted Lyngmo Dec 22 '18 at 02:43
  • 1
    Why friend to `Helper` if you want read-only access in the first place ? Just to get to the private members ? If so why not declare `main_` in `Helper` as `Main const *` ? (friended or not, makes no difference; friending isn't a magic key to unlock an otherwise-const restriction). – WhozCraig Dec 22 '18 at 03:03

0 Answers0