lindelof
lindelof

Reputation: 35250

Why should a pimpl be declared as a struct and not a class?

The canonical form of the pimpl idiom (from Herb Sutter's "Exceptional C++") is as follows:

class X 
{
public:
 /* ... public members ... */
protected:
 /* ... protected members? ... */ 
private:
 /* ... private members? ... */
 struct XImpl;
 XImpl* pimpl_; // opaque pointer to
                // forward-declared class 
};

My question is, why is XImpl declared as a struct instead of a class?

Upvotes: 7

Views: 1334

Answers (3)

The only difference between struct and class is the default access control of the bases and members (public and private, respectively). You can even declare the same type with one and define it with the other (but note that some compilers can issue warnings on this).

Just use whatever is most natural to you. @WhozCraig correctly points out that since XImpl is already inaccessible outside of the implementation X, making its members private by default seems superfluous. Still, as I've said above, it makes no difference here at all, since it's only the keyword used for the definition which matters.

Upvotes: 7

Boris Dalstein
Boris Dalstein

Reputation: 7788

Well... I don't know why Herb Sutter has decided to use struct, but you can use class instead if you prefer, it is equivalent in this case.

Upvotes: 2

Wyzard
Wyzard

Reputation: 34591

It doesn't really make a difference since structs and classes are basically the same, but you probably want everything in XImpl to be public because it's only visible to the code that implements X anyway. Using struct instead of class just saves you from having to write public: at the beginning of its definition.

Upvotes: 2

Related Questions