Passkey Idiom: A Useful Empty Class -- Arne Mertz

logo.pngHow do you share some but not all of a class? Arne Mertz introduces the passkey idiom to avoid exposing too much with friendship.

Passkey Idiom: A Useful Empty Class

By Arne Mertz

From the article:

Let’s have a look at an example for useful empty classes. The passkey idiom can help us regain the control that we give up by simply making classes friends.

The problem with friendship

Friendship is the strongest coupling we can express in C++, even stronger than inheritance. So, we’d better be careful and avoid it if possible. But sometimes we just can’t get around giving one class more access than another.

A common example is a class that has to be created by a factory. The factory needs access to the class’s constructors. Other classes should not have that access so as not to circumvent the bookkeeping or whatever else makes the factory necessary.

The problem with the friend keyword is that it gives access to everything. There is no way to tell the compiler that the factory should not have access to any other private elements except the constructor. It’s all or nothing. 

Add a Comment

Comments are closed.

Comments (0)

There are currently no comments on this entry.