#### Archived

This topic is now archived and is closed to further replies.

# When should I inline, when should I put it in functions.cpp?

This topic is 5900 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

should I inline all my class member functions in the same header file by inlining or put them all in a separate function.cpp?

##### Share on other sites
Its all an opinion... my opinoin is:

Inline = Messy;

##### Share on other sites
Inline when the function is small and you''d like the body to replace its usage in every instance. For example:
int min(int a, int b){  return (a < b) ? a : b;}

This kind of function used to be coded as a C macro, but macros don''t do typechecking (and you have to be careful to parenthesize correctly, or unexpected behaviors could occur. Since it''s such a small function, the overhead of allocating memory on the stack and so forth is so much more than the function body that it''s better to actually place that code everywhere you call min(). In such cases, make the function inline.

Also inline where there may be a lot of compund usage, like arithmetic operators:
class vector3d{public:...inline float &operator[] (int j);inline vector3d &operator*= (float s);// note that the next function is _not_ inlinefriend float &operator* (vector3d &v1, vector3d &v2);...private:  float coords[4];};// inline functionfloat &vector3d::operator[] (int j){  return coords[j % 4];}// inline functionvector3d &vector3d::operator*= (float s){  for(int j = 0; j < 4; ++j) coords[j] *= s;  return *this;}// friend function - dot productfloat &operator* (vector3d &v1, vector3d &v2){  // ignore w-coord; it''s for homogeniety  return (v1[0]*v2[0] + v1[1]*v2[1] + v1[2]*v2[2]);}

The [] operator is better inlined because it is used so heavily in other operators that in-place expansion speeds up execution remarkably.

##### Share on other sites
A good rule of thumb for deciding whether a function should be declared inline or not is that if the code only takes one line, it should be inline''d, otherwise not. In addition, the inline specifier only requests that the compiler inline the function. If the function is too complex for the compile to resolve, whether it fits on one line or not, the compiler will ignore the inline specifier and generate a function call anyway.

• ### Forum Statistics

• Total Topics
628711
• Total Posts
2984342

• 23
• 11
• 10
• 13
• 14