C++ – Why Overloaded Function for Derived Class Object Not Invoked with Base Class Pointer

c++inheritanceoverloadingpolymorphism

In the following code

#include <iostream>
using namespace std;

class A {
  public:
    A() {}
    virtual ~A() {};
};

class B : public A {
  public:
    B() {}
    virtual ~B() {};
};

void process(const A&) {
    cout << "processing A" << endl;
}

void process(const B&) {
    cout << "processing B" << endl;
}

int main(void) {
    A* a = new B;
    process(*a);
    return 0;
}

the output of running it becomes

processing A

but I would have assumed that it should have been

processing B

since a points to the derived class B and not A. So why does it call the first implementation of process function and not the second?

Best Answer

The static type of expression *a is A because a was declared as

A* a = new B;

The compiler resolves the selection of overloaded functions using the static type of the argument.

Even when virtual functions are called the compiler uses the static type of the object to call appropriate function. The difference is only that the compiler uses the table of pointers to virtual functions to indirectly call the required function.

Related Question