Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any use for a class to contain only (by default) private members in c++?

Members of a class are by default private in c++.

Hence, I wonder whether there is any possible use of creating a class that has all its members (variables and functions) set by default to private.

In other words, does there exist any meaningful class definition without any of the keywords public, protected or private?

like image 577
mr_T Avatar asked Sep 11 '25 11:09

mr_T


1 Answers

There is a pattern, used for access protection, based on that kind of class: sometimes it's called passkey pattern (see also clean C++ granular friend equivalent? (Answer: Attorney-Client Idiom) and How to name this key-oriented access-protection pattern?).

Only a friend of the key class has access to protectedMethod():

// All members set by default to private
class PassKey { friend class Foo; PassKey() {} };

class Bar
{
public:
  void protectedMethod(PassKey);
};

class Foo
{
  void do_stuff(Bar& b)
  {
    b.protectedMethod(PassKey());  // works, Foo is friend of PassKey
  }
};

class Baz
{
  void do_stuff(Bar& b)
  {
    b.protectedMethod(PassKey()); // error, PassKey() is private
  }
};
like image 123
manlio Avatar answered Sep 13 '25 01:09

manlio