Search code examples
c++privatefriendpublicprotected

c++ special method visibility


I have a simple object, of type "ObjectX", with a simple method called "doSomething()". I'd like to make doSomething ONLY accessable by other ObjectX's. In other words, if something that is either static, or not an object of type "ObjectX" tries to call doSomething, it will be unable to. However, if an object of type ObjectX tries to call the method, it WILL be able to.

This differs from a private method, in that, a private method can only be called from the same object it is in. If there were another object of the same type calling that method on a different object, it would be locked out.


Solution

  • private does almost exactly what you want. Only objects of the same type can use private methods, and other objects can call those functions on other objects (that is, private functions are not restricted to the invoking object).

    The only thing that is not as you described is that that static functions in the same class can also use private functions. There is no language feature that lets you restrict a function to the object only (excluding static functions).