Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is the virtual method in a simple class really virtual?

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() {}
}
like image 502
user1899020 Avatar asked Nov 18 '25 01:11

user1899020


1 Answers

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.

like image 86
Remy Lebeau Avatar answered Nov 20 '25 14:11

Remy Lebeau



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!