I aware of three different kind of implementation "locations" for my class methods:
1) Define the method inside my class (.h file) and implement it in my .cpp file
//.h
class Foo
{
int getVal() const;
};
//.cpp
int Foo::getVal() const
{ return 0; }
2) Define and implement the method inside my class (.h file).
//.h
class Foo
{
int getVal() const
{ return 0; }
};
3) Define the method inside my class and implement it outside the class but inside my header file.
//.h
class Foo
{
int getVal() const;
};
int Foo::getVal() const
{ return 0; }
What are the main differences between these three approaches?
There are three elements to this question: readability (how good the code looks), compilation (how much the compiler can optimize it) and implementation hiding (If you use the code as a library, you may not want to explicitly share your special sauce with the world).
Method one exposes only the interface for the function in the header file. This means you show a nice clean interface, and your implementation is not exposed in plaintext. However, the code cannot be inlined across compilation units, so it has the potential to be a little slower in runtime (in practice, this only matters for a very, very very small percentage of the code). THIS SHOULD BE YOUR DEFAULT WAY TO GO.
Method 2 is implicit inlining. Long functions will clutter up your class which (imho) is bad. Also exposes your implementation to the world. However, the function can be inlined and is less verbose than defining it in another place. I reserve this for very small functions.
Method 3 is actually illegal, as you will break the one-definition rule, but the following is fine:
//Foo.h
class Foo {
int getVal() const;
};
inline int Foo::getVal() const {
return 0;
}
I use this when I want to keep the class definition clean but want the function definition in the header file (for inlinable or template functions).
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments