C++ virtual function not called in subclass


Consider this simple situation:


class A {
    virtual void a() = 0;


#include <iostream>

class B {
    virtual void b() {std::cout << "b()." << std::endl;};


#include "A.h"
#include "B.h"

class C : public B, public A {
    void a() {std::cout << "a() in C." << std::endl;};

int main() {
    B* b = new C();
    ((A*) b)->a();    // Output: b().

    A* a = new C();
    a->a();           // Output:: a() in C.

   return 0;

In other words:
– A is a pure virtual class.
– B is a class with no super class and one non-pure virtual function.
– C is a subclass of A and B and overrides A's pure virtual function.

What surprises me is the first output i.e.

((A*) b)->a();    // Output: b().

Although I call a() in the code, b() is invoked. My guess is that it is related to the fact that the variable b is a pointer to class B which is not a subclass of class A. But still the runtime type is a pointer to a C instance.

What is the exact C++ rule to explain this, from a Java point of view, weird behaviour?

Best Solution

You are unconditionally casting b to an A* using a C-style cast. The Compiler doesn't stop you from doing this; you said it's an A* so it's an A*. So it treats the memory it points to like an instance of A. Since a() is the first method listed in A's vtable and b() is the first method listed in B's vtable, when you call a() on an object that is really a B, you get b().

You're getting lucky that the object layout is similar. This is not guaranteed to be the case.

First, you shouldn't use C-style casts. You should use C++ casting operators which have more safety (though you can still shoot yourself in the foot, so read the docs carefully).

Second, you shouldn't rely on this sort of behavior, unless you use dynamic_cast<>.

Related Question