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

The canonical form of the idiom pimpl (from Herb Sutter "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 structure instead of a class?

+5
source share
3 answers

The only difference between struct and class is the default access control for databases and members (both public and private). You can even declare the same type with one and define it with another (but note that some compilers may issue warnings on this).

Just use what is most natural to you. @WhozCraig correctly points out that since XImpl no longer available outside of the X implementation, so its private members seem redundant by default. However, as I said above, there is no difference here, since it only matters the keyword used for the definition.

+6
source

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

+2
source

It doesn't really matter, since the structures and classes are basically the same, but you probably want everything in XImpl be publicly available, because it is visible only to code that implements X Using a struct instead of a class will just save you the trouble of writing public: at the beginning of the definition.

+2
source

Source: https://habr.com/ru/post/1202847/


All Articles