fredsch
fredsch

Reputation: 13

Calling pure virtual function in base through instance of derived class

Will the following code require a vtable lookup or can the compiler foresight, which function to call?

class Base
{
    virtual void foo() = 0;

    void bar() {
        this->foo();   // [*]
    };
};

class A : Base
{
    void foo() final {
        ...
    };
};

Base *base = new A();
base->bar();     // sure vtable lookup at [*]!


A a;
a.bar();         // vtable lookup at [*]?

Upvotes: 1

Views: 130

Answers (2)

The answer is that there is nothing in the C++ standard that would require dynamic dispatch in either of the two invocations. If an implementation can prove what function will be called at runtime, it may dispense with dynamic dispatch. For instance, if the call to bar is inlined, the implementation may be made aware that it is invoking foo on an object whose most derived type is A. In such a case it doesn't need to dispatch dynamically.

For the cases where the call to bar is not inlined, the static type of this inside bar will be Base*. Without any knowledge of the most derived object type and the calling context, and given the indirection, an implementation will need to do dynamic dispatch to guarantee correct behavior.

If you want to know how an implementation handles a concrete piece of code, then you may examine the generated assembly, perhaps with a tool like https://godbolt.org. It should make it clear as day what sort of call is being made.

Upvotes: 2

getsoubl
getsoubl

Reputation: 1055

First of all the, you must use protected or public access class modifier before functions definitions . In other case private is the default access modifier and you must set class A : public Base. In addition to this, in the first case in run time the entry in vtable will be use to find the foo function in dervived class (dynamic dispatch). in the second case the function bar is inherited from class A. No dynamic dispatch in this case – getsoubl

Upvotes: 0

Related Questions