C++ – Designing Header Files Like an API

cdesignfile structureheaders

I'm kind of new to large scale software development in C++, and I was wondering on the design side of things.

I was reading this question, and I thought that, overall, once we get past constant definitions and other trivial matters, C++ header files are just API definitions :

They define what other programmers (or yourself from other modules) will be able to use (classes, public functions), but no private class or function should be defined in it.
It's like the header file defines the abstractions (interfaces …) and the source file implements it. Once the source file is compiled, the implementation details are hidden away, and remain the publicly available headers defining what the module can do.

I felt this view of header/source file separation was a lot easier to understand and follow than the usual explanations, since you can just think "would XXX be publicly available API material, or is it a sausage-making detail to be hidden away in an undisclosed source file ?"

Is my mental model of header files roughly correct ?
What did I miss ?

Best Answer

It's not a bad mental model to use as a guide but unfortunately for historical / technical reasons C++ headers conflate interface and implementation in ways that this simple mental model doesn't fully capture.

In order to make good physical design decisions when things get a little more complex, it is generally necessary to understand the way headers work in C++ at a more detailed level.

To give an example: from your API view, a header file should not include the definition of a private implementation class. In practice however, such class definitions will often appear in a header file since the compiler will need to know their size if they are contained in any public classes. Techniques exist to break this kind of dependency but they generally impose a cost in terms of code complexity, performance or both. Understanding when it's appropriate to use one of these techniques requires a deeper understanding of how headers work in C++.