+ 3

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?

26th Mar 2020, 1:26 PM
CodingPro
CodingPro - avatar
1 Resposta
+ 4
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!
26th Mar 2020, 2:32 PM
Arsenic
Arsenic - avatar