user3834847 user3834847 - 1 year ago 73
C++ Question

Devirtualise Child Class Call

Let's say I have a Parent class that implements a virtual method, overridden by a Child class. I understand that if the method is called on a variable of type Parent then the compiler must use some way of checking which implementation of the method should be called at run time, but surely this is not necessary if the variable is of type Child? In this case, assuming that the method is not overridden again by a child of Child, will the compiler devirtualise the method since it is known that the variable will definitely contain a Child, and is this compiler specific?

Answer Source

In order to de-virtualize a call, the compiler would have to know for certain that there are no derived types of Child that it might be passing through the code with:

void f(Child* c) {
    Child* l = new Child;

The c call to virtFn could be for a derived type, but the l call can't.

C++11 introduced the final keyword that can assist with this and allow the compiler to devirtualize calls through a terminal class pointer/ref.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download