Placing Functions inside class vs outside

I see that a function can be coded directly in side a class--or--a model/header can be defined inside the class an the body of the function defined outside the class using double-dots to associate the body with the proper function. https://www.onevanilla.one/

Is there a preference here? It is not clear how memory is allocated, inline-assembler generated etc.


Last edited on
The code generated by the compiler is the same no matter where the actual class method is defined.

Inline status is best determined by the compiler, a programmer inlining a function should be a suggestion to the compiler. The compiler can inline a function that isn't declared as inline, and ignore a request to inline.

Preference? For me it depends on the phase of the moon as well as other "spur of the moment" considerations. The biggest determinant is whether the class being created could be reused outside the current project.

Usually I declare a class method as a stub within the class declaration and define it outside the class declaration. If the class is header-only the method definition is explicitly declared online.
for me, it is by size. If the class only has a few methods or they are all a line or two, I do it all in one block. If it is complicated and large, it gets a .cpp file. The cutoff is .. just whatever you as the coder feels is appropriate.

One of the best things you can do when writing code is ask yourself, critically and as if you were not the author, "if I had to read this code, figure it out, and understand it, does this style work?!".
That will help you decide which way to write it.
One caveat is that it can make a difference if you don't have LTO (Link-Time Optimization) enabled. It won't inline calls in between object files, to my understanding.
Topic archived. No new replies allowed.