In the following code, it calls a virtual function foo via a pointer to a derived object. Will this call go through the vtable or will it call B::foo
directly?
If it goes via a vtable, what would be a C++ idiomatic way of making it call B::foo
directly? I know that in this case I am always pointing to a B
.
Class A
{
public:
virtual void foo() {}
};
class B : public A
{
public:
virtual void foo() {}
};
int main()
{
B* b = new B();
b->foo();
}
Working of virtual functions (concept of VTABLE and VPTR)If object of that class is created then a virtual pointer (VPTR) is inserted as a data member of the class to point to VTABLE of that class. For each new object created, a new virtual pointer is inserted as a data member of that class.
A virtual function is a member function that you expect to be redefined in derived classes. When you refer to a derived class object using a pointer or a reference to the base class, you can call a virtual function for that object and execute the derived class's version of the function.
The vtable contains an entry for each virtual function accessible by the class and stores a pointer to its definition. Only the most specific function definition callable by the class is stored in the vtable.
Most compilers will be smart enough to eliminate the indirect call in that scenario, if you have optimization enabled. But only because you just created the object and the compiler knows the dynamic type; there may be situations when you know the dynamic type and the compiler doesn't.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With