Search code examples
c++constructorvirtual-functionsvtable

why is the base function called instead?


In the following code:

#include <iostream>
using namespace std;

class A {
    public:
    A() {
        cout << " A constructor \n";
        sum(2,4);
    }
    virtual int sum(int a, int b){
        cout << "Base sum \n";
        return a + b;
    }
};

class B : public A {
    public:
    B() : A() {
        cout << " B constructor \n";
    }

    int sum(int a, int b){
        cout << "Overloaded sum \n";
        return (a + b) * 10;
    }
};

int main(){
    A* a = new B();
    // a->sum(4,5);
}

Why is A's sum invoked even though I have marked it as virtual and overloaded it in B ? At runtime, with the help of vtable shouldn't B::sum() be invoked ?


Solution

  • Because by the time you call the method, a isn't an object of type B yet.

    Avoid calling virtual methods from constructors: it will lead to unexpected results (unless of course you expect this exact behavior, in which case you'd be spot on).

    At runtime, with the help of vtable shouldn't B::sum() be invoked ?

    Not really, because the object doesn't have the vtable of B at that point.