After a few years of not working with it much, I'm getting back into it, mainly for a few possible job prospects. The part I'm having difficulty remembering and figuring out again is the general "best practice" for file/class structuring.
One specific is where and how to define functions in a class. I've seen several examples where they are defined like:
1 2 3
class foo {
public:
void bar (int);
And then outside the body of the class, they're defined as:
1 2 3
void foo::bar (int i) {
...
}
Other times, I see them fully defined inside the class structure. Is it preferred to use header files to define them and skip the first example's way of doing it?
I'm just trying to relearn the best techniques for defining headers and files, along with the classes and functions within. Any advice or links to good articles would be appreciated, thanks!
If I recall correctly, the reason you would declare it within the class and not within has something to do with how the compiler builds the program.
I hope others correct me if I am wrong, but I believe it goes as such:
If it is declared within the class, then the compiler builds each inline function (members within a class definition) every time the function is called at each location. Thus, doing this eliminates calling copy constructors and destructors and all that fun stuff, making the program more bloated, but more efficient.
Declaring it outside then passes parameters and returns them as you would a regular non object oriented function. Copy constructors and destructors are called, code is less bloated, but less efficient.
I really hope I declared that correctly, I know this whole question revolves around how the compiler assembles the code, but I may be off on what actually happens.
Putting the definition (the code) of a method inside the class makes the method inline. This lets the compiler put the code directly into the calling function, which can result in better optimization. This is nice when the code is very short.
Unless it's just a line or two, I always separate the declaration of the method from the definition. The main reason is so that someone reading the class declaration can tell what the methods are and how to use them. If the code is contains within the class declaration then the poor reader has the dig through all your code to figure out which methods are available.