1

I want to limit the amount my classes know about each other, even two instances of the same class. How can I pass a whole object as a parameter to a method, at the end return that object, not be able to access its private fields, and being forced to use getters and setters?

The Stack Overflow Why do objects of the same class have access to each other's private data? Q&A talks about why you cannot have instantiated object prohibit each other from accessing private fields. However, it does not contain possible fixes to the problem.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
  • 1
    AFAIK, There aren't any fixes. All objects of a class type have access to each others stuff. You would need to establish code review to make sure that you access everything via getter and setters. Or you can make each object a unique type, then they wont have access. – NathanOliver Jul 22 '21 at 18:43
  • “Or you can make each object a unique type” Thats probably what I’ll have to do. – Zach Hebert Jul 22 '21 at 18:50
  • free your functions. You cannot access private members is free non-member functions. Make only functions that must be members members of the class. – 463035818_is_not_an_ai Jul 22 '21 at 18:57
  • 3
    btw it is not clear why you consider it as a "problem". Can you show some code example of what you would like to prevent? – 463035818_is_not_an_ai Jul 22 '21 at 18:58
  • 1
    It's worth mentioning that what you are trying to prevent is often critically important in making proper move constructor/assignment. Even if you did succeed, you might very well regret it later. –  Jul 22 '21 at 19:00
  • 1
    `class MyClass { public: MyClass(); ~MyClass(); int GetFoo() const; void SetFoo(int); void SomeOtherFunct(MyClass const&); private: class Internals; std::unique_ptr m_internals; };` if you do something like this you could split the implementation to 2 translation units: one for declaring `MyClass::Internals`, the constructor, desturctor and the setters and getters and one for the other functions. I'm afraid it won't get any better than this. You could of course also replace`Internals`with a class that has several member functions of`Internals`as friends. Seems pretty paranoid though – fabian Jul 22 '21 at 19:00
  • The mental model is not "one programmer per object". It is "one programmer per class". (Even if you write all the classes alone, while writing class A you pretend to only know about public parts of classes B, C and D, but you have to know everything about the class you are writing). The programmer writes the code of the class, and is responsible for the behaviour of the entire code of the class. Individual objects don't have their own code so it doesn't make sense to place separate requirements on individual objects. – n. m. could be an AI Jul 22 '21 at 19:38

0 Answers0