Akash
Akash

Reputation: 5012

Dynamic binding in virtual functions C++

I have a base class with 1 virtual function

class Base
{
public:
    virtual void print() {
        cout<<"IN BASE\n";
    }
}

Now I create its object using

Base b

and Call

b.print();

Is this dynamic binding, as the "Base" class contains 1 virtual function and its VTable is created..

Upvotes: 0

Views: 390

Answers (2)

Seva Alekseyev
Seva Alekseyev

Reputation: 61380

The term "dynamic binding" typically means something else - the plumbing that lets you call functions from external files (DLL's or SO's) as if they're a part of your executable.

The class Base has a vtable all right - after all, while compiling the current file, the compiler can't know for sure if there are any derivatives of it elsewhere in the project.

Now, whether the call follows the vtable is an implementation detail - it depends on compiler and settings. On one hand, it should. On the other, if the object is automatic like this, its type is known at compile time, and cannot possibly be other than Base. A good compiler might optimize the vtable lookup away.

Building with assembly listing enabled will show you for sure.

Upvotes: 0

In the same context where the object is created, the compiler does not need to use virtual dispatch as it knows the exact type. But that is unrelated to the number of virtual functions (and yes, as long as there is at least one, the compiler will generate a vtable and store a vptr in your object).

Base b;
b.print(); // can be optimized to b.Base::print(),
           // with no virtual dispatch

void f( Base& b ) {
   b.print();       // must use virtual dispatch (ignoring potential inlining)
}

Upvotes: 4

Related Questions