Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 313
lindelof Avatar asked Sep 18 '14 07:09

lindelof


1 Answers

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.

like image 78
Angew is no longer proud of SO Avatar answered Oct 01 '22 06:10

Angew is no longer proud of SO