0

次のコードで:

#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);
}

仮想としてマークし、Bでオーバーロードしたにもかかわらず、Aの合計が呼び出されるのはなぜですか?実行時に、vtableの助けを借りてB :: sum()を呼び出すべきではありませんか?

4

2 に答える 2

5

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.

于 2012-08-09T05:53:32.973 に答える
0

派生クラスをインスタンス化すると、基本コンストラクターが最初に実行されます。つまり、基本コンストラクターの実行中、派生オブジェクトの構築はまだ完了していません。

コンストラクターのアクションを意図したもの、つまりオブジェクトの初期化に制限することにより、これらのシナリオを回避します。

于 2012-08-09T05:59:26.613 に答える