Yawn
Yawn

Reputation: 81

Do I have to define classes in header files in C++?

I am new to C++ so please be kind. I was wondering if we really have to put classes in headers files (.h) . I know it looks better and is more efficient to separate the definition with the implementation but is there another benefit of doing this such as faster compilation or something like that?

Anything would help, thanks!

Upvotes: 0

Views: 110

Answers (2)

Saeed All Gharaee
Saeed All Gharaee

Reputation: 1683

Actually you don't have to. However using header files has following benefits:

  1. Enables you to find your classes easier by choosing your desired file rather than time consuming scrolls.
  2. Your code is easy to maintain, meaning that developing process is easier and faster in the future.
  3. It potentially can reduce compiling time, because instead of loading whole code it loads the required ones.

Upvotes: 1

Aykhan Hagverdili
Aykhan Hagverdili

Reputation: 29955

All classes must be fully defined in every translation unit that uses objects of that type. You must make sure that these are all identical, or else the behavior of the program is undefined. And when you make some change to any of the definitions, you must change all others accordingly.

Someone came up with the idea of putting all class definitions in a single file, and using the preprocessor to copy+paste it everywhere we need those classes. This is the #include "file" directive which basically replaces this line with the contents of file.

Upvotes: 1

Related Questions