Java vs. C++

Started by
12 comments, last by TheBluMage 19 years, 4 months ago
Quote:Original post by Drakkcon
every time you define a function within your class header instead of its implementation, the function is automatically declared inline.

Come on guys. Compilers are smarter than you know.
Advertisement
Quote:Original post by C-Junkie
Quote:Original post by Drakkcon
every time you define a function within your class header instead of its implementation, the function is automatically declared inline.

Come on guys. Compilers are smarter than you know.


Well, if I programmed it, then it wouldn't be very smart, so it depends on what compiler you use. Smart compilers don't always inline even if you tell it to always inline because they are smarter than YOU :)
Ok I am still in the process of learning C++ and am now very confused. Why does it matter if class functions are declared inline or not? It is my understanding that inlining is used for function calls like so

void g(){

blah...
blah...
h(blah, blah); <-- function call
blah..
h(blah, blah); <-- function call

}

So now if h() is inline with g() the program will run faster because there aren't excessive stack pushes and pops, but if it's not inline the code will be smaller and take longer to run. So why does it matter for a class declaration where everything is declared only once? Is it because if the function is inline in the class declaration it will be declared inline when it is called in another function? Ahh that would make sense..

So if that is the answer I dont think anyone can say whether inlining is good or bad absolutely. Increased speed may be desirable over bloated code... Thoughts?
Inlining is perfect for small functions that are around 1-3 lines long. For large functions, though, they can and do lead to code bloat if they are called at many places. When a function is inlined, the whole function is essentially copied to wherever the function is "called". This not only leads to a larger executable, but can also make it so that the processor needs to load code into its cache more frequently than normal, causing a loss in performance.

Most decent compilers won't care where you put the implementation and will decide to inline by themselves, but since the original standard was that the functions implemented inside the class got inlined, I tend towards implementation outside the class. Personally, I think this keeps the code more organized, but that's just my opinion. When I was learning C++ (with a C# and Java background) at first I prefered implementation inside the class, but after using C++ a bit more, the other method soon became more natural and now, even for functions I want inlined, I implement them outside of the class and use the inline keyword instead. (Again, just a personal preference, but it just goes to show that a new language can change your programming style if you give it enough time.)

This topic is closed to new replies.

Advertisement