Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is better practice when programming a member function?

I have seen member functions programed both inside of the class they belong to and outside of the class with a function prototype inside of the class. I have only ever programmed using the first method, but was wondering if it is better practice to use the other or just personal preference?

like image 253
Matt Pascoe Avatar asked Dec 01 '22 08:12

Matt Pascoe


2 Answers

Assuming you mean C++, it is always better to define functions outside of the class, because if you put it inside the class, compiler may try to inline it, which is not always desirable:

  1. Increase in code size (every object file that includes this header might end up with a copy of the function in their code).
  2. Breaking binary compatibility when function definition changes.

Even with inline functions, it is usually better to put definitions outside the class to improve readability of class public interface, unless the function is a trivial accessor or some other one-liner.

like image 165
Alex B Avatar answered Dec 10 '22 22:12

Alex B


For C++, putting method definitions in the header file means that everything that includes a given header must be recompiled when the header changes - even if it's just an implementation detail.

Moving definitions out of the header means that files which include the header will need to be recompiled only when the header itself changes (functions added/removed, or declarations changed). This can have a big impact on compile times for complex projects.

like image 28
nobody Avatar answered Dec 11 '22 00:12

nobody