1

Say I have the following:

struct Base
{
    virtual void callback() { /* */ }
};

struct Derived : public Base
{
    void callback() { /* */ }
};

Base* obj = new Derived;
static_cast<Derived*>(obj)->callback();

Will the call to callback invoke via the vtable or a straight function call as it's not marked as virtual in the function signature?

0

1 Answer 1

4

Derived::callback is implicitly virtual because the Base::callback function with a the same return type and parameters is declared as virtual.

That said, whether or not the vtable is used depends on the compiler and what optimizations it performs. Since the compiler can know here that obj points to a Derived object, it knows what the final overrider for the callback virtual function is, so it could potentially make the call without looking up the function in the vtable. Whether or not it does so depends on the compiler and optimization settings, though.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.