Punit Salian
Punit Salian

Reputation: 41

Is it good C++ to define classes in .cpp file?

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?

Upvotes: 0

Views: 1854

Answers (1)

Basya
Basya

Reputation: 1485

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.

Upvotes: 3

Related Questions