Reputation: 369
Writing a function in a .h file and its implementation right after (implicit inline), while using the virtual keyword:
virtual void g(){cout<<"is Inline?"};
Is the virtual functionality meaningless because the function is implemented in the .h? Is this considered to be an inline?
Upvotes: 1
Views: 854
Reputation: 254461
Is the virtual functionality meaningless because the function is implemented in the .h?
No. virtual
and inline
are completely independent concepts.
virtual
means that the function to call is chosen, at run-time if necessary, according to the dynamic type of the object it's invoked on.
inline
means that you're allowed to define the function in more than one translation unit, and must define it in any translation unit that uses it. This is necessary (for some compilers) to allow the function to be inlined, but does not force all calls to be inlined. In particular, virtual calls usually won't be inlined (unless the dynamic type can be determined at compile time), so virtual
will certainly retain its meaning here.
Is this considered to be an inline?
Yes, but (as mentioned above) that does not mean that all calls will be inlined.
Upvotes: 7
Reputation: 11028
If you declare your function virtual
, it is virtual, period. But, since virtual functions are usually selected at runtime, usually the compiler will not be able to inline them. If you call the function on an object, the compiler may inline it, since the call can be resolved at compile time. But it won't be able to inline a call through a reference or pointer, since it cannot resolve the dynamic type at compile time.
Take into account that neither the inline
keyword not the implicit inlining here are mandatory for the compiler; they are just suggestions. But the virtual
keyword is mandatory.
Upvotes: 0
Reputation: 69988
Is the virtual functionality meaningless because the function is implemented in the .h?
Nope. No reason to feel so. Header file is preprocessed and copy-pasted wherever it's included. So ultimately it's as good as implementing your g()
in whatever .cpp file.
Is this considered to be an inline?
Yes. But here the inline
doesn't mean usual interpretation of replacing function call with its content. virtual
function resolution happens at runtime, so that can definitely not be inlined in that (macro style) way.
It means, that compiler guarantees to generate only 1 definition for all translation (.cpp file) units. Thus linker will not complain about multiple definition errors.
Upvotes: 1