Possible Duplicate:
Pure virtual functions may not have an inline definition. Why?
Just as the title says, why? And how about (not pure) virtual function, can it be inline format? And I'd like to know the real reason. Thanks!
Possible Duplicate:
Pure virtual functions may not have an inline definition. Why?
Just as the title says, why? And how about (not pure) virtual function, can it be inline format? And I'd like to know the real reason. Thanks!
A virtual function 99% of the time cannot be inlined
because the function pointer is resolved at runtime using vtable
.
The purpose of a virtual function is to be overloaded by subclasses. An example :
class A
{
virtual int foo() { return 1; }
}
class B : public A
{
virtual int foo() { return 2; }
}
int main(void)
{
B b;
A *a = &b;
return a->foo();
}
The main function will return 2 and not 1.
If the compiler inline the function it will return 1 because the compiler can only assume that the type of *a
is A
and not B
. So the compiler will not do it if he cannot assume safely the type of *a
.
In this example the compiler may successfully and safely assume that virtualization is not needed : This is really depending of the compiler and of optimization level.
In some case the compiler can safely assume that virtualization is not needed and only in these cases the inline keyword makes sense.
Even if you declare a function with the keywords inline
, the function may not be inlined.
Anyway adding manually the inline
keyword is most of the time not a good idea, compiler today are good and automatically inline function when necessary.
By adding inline
you may in some case decrease performance, so it a good practice to not abuse of it
Well, a pure virtual function certainly can be marked inline.
struct Base
{
virtual void Func() const = 0;
};
inline void Base::Func() const
{ std::cout<<"Base\n"; }
struct Concrete : Base
{
virtual void Func() const;
};
inline void Concrete::Func() const
{ Base::Func(); std::cout<<"Concrete\n"; }
Also, virtual functions can be inlined (which is not very closely related to the inline
keyword) in cases where the compiler can statically determine the function that needs to be called. For example:
int main(void)
{
Concrete o;
o.Func();
}
Complete demo: http://ideone.com/zlxn8I
And see this related question: LTO, Devirtualization, and Virtual Tables