Is it bad if I define class methods in .h file? | Sololearn: Learn to code for FREE!


Is it bad if I define class methods in .h file?

I know the concept of header file, I am just wondering is it bad if I define class methods in .h file instead of .cpp? I have some very short class method definition, especially constructor, destructor and getter methods and I define them in .h files. For example, In .h, in class definition, I put string getName() {return name;} Should I only declare all the methods in .h and only define in .cpp? Why?

3/26/2020 1:26:53 PM


1 Answer

New Answer


I think there are 2 reasons for that:- First:- functions defined inside the class are implicitly inline. For larger functions that are called from many places, this can bloat your code. Second:- if you change anything about the code in the header, then you’ll need to recompile every file that includes that header. This can have a ripple effect, where one minor change causes the entire program to need to recompile (which can be slow). If you change the code in a .cpp file, only that .cpp file needs to be recompiled!