Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does C++ virtual function call on derived object go through vtable?

Tags:

c++

virtual

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();
}
like image 403
aaa Avatar asked Dec 16 '10 18:12

aaa


People also ask

How virtual keyword works in the backend concept of vtable and _vptr?

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.

What happens when a virtual function is called?

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.

What is stored in vtable?

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.


1 Answers

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.

like image 85
Ben Voigt Avatar answered Oct 04 '22 10:10

Ben Voigt