Click here to Skip to main content
15,887,683 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
So I've dived into OOP after quite some time, and I stumbled upon another one of these "good practices" that help you make your code look cleaner better etc.

So inline methods.

I know that inline methods are methods that are not just declared but also defined in the class itself.

I heard we should define them inline only if we have smaller pieces of code.

So my question is?

What is meant when said smaller methods?

Does it mean constructors, destructors, etc. methods without anything really in them, quite frankly we can create an initialization list and have no single parameter inside a constructor.

But then again that would mean separating the code, longer methods in .cpp and
smaller just inline in the .h

Which looks cleaner? more readable?

What I have tried:

Tried both methods, and would like to know which looks cleaner.
Posted
Updated 6-Mar-16 2:28am
v2
Comments
[no name] 6-Mar-16 8:26am    
This does not make a lot of sense. Inline has nothing to do with cleaner code. Why not read this answer and think about the question some more: http://stackoverflow.com/questions/145838/benefits-of-inline-functions-in-c

1 solution

Inline functions have nothing to do with "looking cleaner", or "more readable" - they are a performance tuning feature. Basically, an inline function is telling the compiler "I'm going to be doing this a lot and I need it quick" - so it doesn't add the overhead of parameter passing and a function call, but whenever you call the function is inserts the actual code directly into your current function instead of stacking parameters, saving the return address, and calling the method. It decreases execution time, at the expense of code size, because every time you call the function the same code is inserted. So call it thousands of times in a single loop and you save time for little or no code size cost. Call it from thousands of different places in your code, and you will save a little time - but it may not be that noticeable - at the cost of thousands of copies of the same code being in your final application.

That's why you only use it for small pieces of code: because otherwise it can enlarge your executable for no real gain.

So:
Small code, often called in a loop, rarely called as a one off - then make it inline.
Large code, called from lots of places, rarely called in a loop - don't inline it.
 
Share this answer
 
Comments
nv3 6-Mar-16 10:13am    
Nice explanation!
barneyman 6-Mar-16 16:04pm    
also worth pointing out that some optimisers will consider the inline keyword a suggestion, and may decide not to honour it

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900