简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM