Possible Duplicate:
In C++ why have header files and cpp files?
I don't quite get C++ header files, for two conflicting reasons:
I thought the purpose of header files was in general to separate interface and implementation. In other words, the client uses the header file to learn how to use the class, but doesn't have to worry about how the class actually implements this functionality internally.
Why, then, are private variables of a C++ class specified in its header file?
It seems to me that having private variables in the header file violate the separation of interface and implementation. Intuitively, I would think it would make more sense for private variables to be in the source file, since this is the file that is not exposed to the outside world.
Maybe I'm just misunderstanding the purpose of header files, and 1. above is just completely wrong? In what ways?
The primary functional purpose of C++ header files is that in the C++ language there aren't module imports or anything similar that exist in other languages. The only way for the compiler to know about types, functions, etc from other files is to paste the code into the current source file by using #include
.
Theoretically you could put all your source code into the header as well and just have one source file that includes all the headers. The reason this isn't usually done is twofold. First, it would take longer to compile (a significant concern on some projects) and any change to any file would result in a complete recompilation of the project. Secondly, putting the implementation into a source file does in fact help separate the interface from the implementation, even if a portion of the implementation is still specified in the header file.
Note that inline methods in headers also walk a fine line of implementation detail exposed to the public/clients of your class.
If you really wish to completely separate the interface from the implementation (which has definite merit) the C++ way to do so is to utilize the pimpl idiom. Using that idiom all the private data is hidden away in the source file and only an abstract interface is provided to the public. Additionally using the non-virtual interface (NVI) pattern can further help isolate clients from interface changes.
C++ distinguishes between declaration and definition of functions and classes. In general a C++ header file contain the declaration of a class. Since no partial declarations are allowed the header file needs to contain the complete class declaration including all private members (variables and member functions).
If you want to hide the complete implementation from the public you can use the pimpl idiom to achieve this.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With