Why inline keyword should used in the definition of member function. and Not in declaration?
inline
has some pre-historic use, but nowadays it's best to remember it as saying: "this definition is going to be defined multiple times, and that's okay."
That is, normally the one-definition rule prohibits multiple definitions of a function. This:
// foo.hpp
void foo() { /* body */ }
// a.cpp
#include "foo.hpp"
// b.cpp
#include "foo.hpp"
results in an error, as foo
is defined in two translation units. You can declare things as often as you want. This:
// foo.hpp
void foo();
// foo.cpp
void foo()
{
/* body */
}
// a.cpp
#include "foo.hpp"
// b.cpp
#include "foo.hpp"
is fine, as foo
is defined once, and declared multiple times. What inline
does is allow this:
// foo.hpp
inline void foo() { /* body */ }
// a.cpp
#include "foo.hpp"
// b.cpp
#include "foo.hpp"
to work. It says "if you see foo
more than once, just assume they are the same and be okay with it".
No, it can be used in the member function declaration also. Though msdn documentation isn't standard, it is mentioned MSDN inline. See the note part in it.
But, I learnt that it is up to the modern compilers to make a function inline or not despite explicitly mentioning inline.
class foo
{
inline void methodOne();
};
void foo::methodOne()
{
}
IdeOne Results
Also, one can specify it both declaration and definition to have the same effect.
class foo
{
inline void methodOne();
};
inline void foo::methodOne() // Here keyword inline is optional. Needs to be mentioned if method declaration isn't declared inline.
{
}
IdeOne Results
Both of the above will have the same effect.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With