In C# or Java, classes are declared and defined at the same time. In C++, the norm is to do that separately. What if we write the whole class in one , say .cpp, file and include that in files that references to it, what kinds of bad thing technically would happen besides a lengthened compilation process?
Share
If your implementation of
MyClassis all in the header fileMyClass.hthen any file you needed to implementMyClasswill be included whenever someone includesMyClass.h.If you change any part of
MyClass.h, even if it’s trivial (such as adding a comment or even a space) then all files that include it will have to recompile, even if the interface hasn’t changed.Neither of these matters for toy projects, but as you noted, when you have a program that consists of hundreds (or thousands, etc.) of class files, the added compilation time alone makes it worthwhile to separate out implementation from interface.
For instance, if I have the following:
It would more ideomatically be written as:
Notice: Including
MyClass.hdoesn’t meaniostream,iomanip,sstream,string, orInventory.hhave to be parsed. Changing howprocessInventoryworks doesn’t mean all files usingMyClass.hhave to be recompiled.Notice how much easier it can be to figure out how to use
MyClassnow. Header files serve an important purpose: they show people how to use your class. With the modifiedMyClass.hit’s easy to see the list of functions. If each function is defined in the header, then you can’t look at just the list of functions. That makes it harder to figure out how to use the class.