46

Is there a way to hide private data members of a C++ class away from its users, in the cpp file? I think of the private members as part of the implementation and it seems a little backwards to declare them in the header file.

Jeff Linahan
  • 3,775
  • 5
  • 37
  • 56

5 Answers5

66

The "pimpl" idiom is how this is generally handled.

See

Adrian McCarthy
  • 45,555
  • 16
  • 123
  • 175
Kristopher Johnson
  • 81,409
  • 55
  • 245
  • 302
  • Thanks, it works now. Those two articles explain the idiom well. – Jeff Linahan Oct 15 '08 at 20:51
  • In general, yes this could have a performance impact, as there is a pointer dereference involved whenever the private stuff is accessed. However, a compiler may be able to optimize it such that the impact is negligible. – Kristopher Johnson Jan 31 '13 at 21:48
  • 1
    Can you explain this in your answer instead of just posting links? The links may one day change or disappear. – TomE Dec 17 '21 at 00:20
11

you want to use something like the PIMPL idiom

http://en.wikipedia.org/wiki/Opaque_pointer

Keith Nicholas
  • 43,549
  • 15
  • 93
  • 156
8

See Pimpl Idiom

Nemanja Trifunovic
  • 24,346
  • 3
  • 50
  • 88
4

The classic way to do this is with a proxy pointer to an internal class which implements the functionality. There's no way to do partial class definitions in C++ that I know of.

Nick
  • 6,808
  • 1
  • 22
  • 34
1

Going commercial? ;)

You can create header files, in which you only declare the public and protected API.

The user is only presented with these, which they can include. They link their code with a library, which you built using the complete API and the definitions.

For inlined functions: make sure they are used in non-inlined code, then there will be a definition available in the library (I'm not sure it will be inlined in the user implemenation, however).

For templated code there is no real way around. One half-hearted solution is to make code, which uses the templated code with different object types. The user will be limited to these, because they are the only definitions available in your library.