Search code examples
c++polymorphismdispatch

Does dynamic dispatch come into play when I have a concrete type?


Lets say I have a class Interface which provides pure virtual functions.
Now lets say I have two classes Concrete1 and Concrete2.

I instantiate them like this:

Interface* impl = createConcrete1orConcrete2(); // randomly select Concrete1 or Concrete2
Concrete1* concrete = new Concrete1();
impl->foo();
concrete->foo();

Will concrete make use of dynamic dispatch?


Solution

  • Compiler has to do the dynamic dispatch, but following the as-if rule, it might devirtualize the call if it know the final dynamic type as optimization.

    Here indeed, with new Concrete1();, dynamic type is known.

    But for Concrete* ConcreteFactoryCreate(), it wouldn't (Concrete might still have derived classes) unless the help of final on the class or on the method.