0

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..

1
  • It would be dynamic binding if you had multiple base classes and had to convert an instance of a derived class to a base class and then call a virtual member function of that base class. Commented Aug 3, 2012 at 17:56

2 Answers 2

4

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)
}
Sign up to request clarification or add additional context in comments.

2 Comments

thanks. If I had a 3 derived classes from it, and If I would have called "Derived1 d; d.print()" with print defined in the derived class too, could be considered as a case of Dynamic Binding
@Akash: The term is dynamic dispatch, and if the object is created in the same scope as the call, then the compiler knows what the result of the dynamic dispatch will be and can optimize it away, calling the proper function. This is irrelevant of what the exact type of the object is, since the compiler knows that exact type.
0

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.

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.