0

I am a beginner in C++. I have a question regarding C++ design.

My file contains A,B,C,D,E class definitions. Class A contains the API which is used by other applications. I have defined this in a .h file. Classes B,C,D & E define concrete classes by inheriting an abstract class which is provided by some library. These definitions are not used by any external application, but only used by class A.

I have seen online that all the class definitions are provided in an .h file and the function implementations in a .cpp file. My question here is, even though class B,C,D & E definitions are not used externally by anyone, should I define them in the .h file? If I do define them there anyway, I cannot expose them to other applications, right?

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770

1 Answers1

3

If a class is only used locally in one module, you can declare it in the .cpp file. This is actually good practice; don't expose more than necessary.

In a case where you need to define a class (or function, etc.) in a header (for example, to share it between several related .cpp file) but you do not want to expose it publicly, you can have a separate, private header file which is only included in the relevant places, but is not made public. This can be hinted at by appending "private" to the header file name.

Basya
  • 1,477
  • 1
  • 12
  • 22
  • Another techniques to hide implementation details (even from the linker) is to use [anonymous / unnamed namespaces](https://stackoverflow.com/questions/357404/why-are-unnamed-namespaces-used-and-what-are-their-benefits) (better than "private header"). May be worth mentioning to improve your answer. – πάντα ῥεῖ Sep 10 '20 at 19:02
  • @πάνταῥεῖ -- if I understand correctly, anonymous namespaces will limit access to one translation unit -- how does that replace the private header, which limits use to several, related, translation units? – Basya Sep 10 '20 at 20:53
  • 1
    Seems I didn't read properly that you proposed more than one unit. In that case anonymous namespaces won't help. You're right about that. – πάντα ῥεῖ Sep 10 '20 at 21:18