Reputation: 13575
I have a simple class, which has no derived types and no inheritance relations with other classes.
class A
{
virtual void f() {}
}
I am wondering if the "virtual" method in fact is not really virtual, so the class is the same as
class A
{
void f() {}
}
Upvotes: 2
Views: 111
Reputation: 596437
YOU know there is no derived types. The COMPILER doesn't know that. Such types, if ever defined, would be defined at a later time after A
is defined.
So, at the point wherever A
is used, f()
has to be treated as virtual UNLESS the compiler can prove otherwise, for example when calling f()
on a statically-typed A
object, eg:
A a;
a.f();
In this context, the compiler can call A::f()
statically, because it knows it can't possibly call anything else.
But when calling f()
through an A&
reference or an A*
pointer instead, the compiler will have to use a virtual dispatch, since the compiler can't know exactly what type of object is being used at runtime.
Upvotes: 12