2

First things first: I know thats it's quite probable that my question is based on a general missunderstanding, but I hope I can make my point clear to you.

I know that when putting code into diffrent files in C++ we have do create a .h (for Definitions) and a .cpp (for implementations). When writing a class-library for example I have to put a definitioj of both, private and public members in the header. But what to do if - for some reason - I want to hide the private things from the user?

Thanks!

PEAR
  • 627
  • 2
  • 9
  • 17

2 Answers2

5

You use the Pimpl idiom. Pimpl stands for "pointer to implementation". Basically, you don't store the implementation details in the class. Instead you store an opaque pointer to implementation as such:

class MyClass
{
public: 
    //public functions here
private:
    class Impl; //no definition, opaque
    Impl* pimpl;
};

And then you go on to define your MyClass::Impl class in the .cpp file only, because only the function definitions need it.

The PIMPL idiom has the additional benefit that as long as the interface of the class does not change, any changes made to the implementation do not require the recompilation of class clients.

Armen Tsirunyan
  • 120,726
  • 52
  • 304
  • 418
4

You can't. This is one of the drawbacks of C++: things marked private are still part of the class declaration and so will be present in the header.

If you really want to hide the functionality, then using the pImpl Idiom can help. Personally though I prefer to live with the drawback as using the idiom can cause other problems such as your class no longer being trivially copyable.

See Why should the "PIMPL" idiom be used?

Community
  • 1
  • 1
Bathsheba
  • 220,365
  • 33
  • 331
  • 451