7

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?

lindelof
  • 31,966
  • 30
  • 87
  • 133
  • 4
    There is little sense is hiding something that is already hidden. The default access of `private` for a `class` vs. `public` for a `struct` seems trivially overkill. – WhozCraig Sep 18 '14 at 07:21
  • 3
    It makes absolutely no difference whatsoever (unless your compiler is very very buggy). – Marc Glisse Sep 18 '14 at 07:23
  • @WhozCraig But that is a forward declaration. In this particular case, it makes absolutely no difference. It doesn't even save typing :-) – juanchopanza Sep 18 '14 at 07:31
  • @juanchopanza I completely agree. its the language-difference of the word as a normal decl I was commenting on. you're absolutely right that it truly makes no functional difference at all. – WhozCraig Sep 18 '14 at 07:33

3 Answers3

7

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.

Angew is no longer proud of SO
  • 156,801
  • 13
  • 318
  • 412
2

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.

Boris Dalstein
  • 5,395
  • 3
  • 26
  • 48
2

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.

Wyzard
  • 31,764
  • 3
  • 60
  • 78