SantaXL
SantaXL

Reputation: 664

Virtual inheritance - why this output

Take a look at the code below. Why the output from static_cast<D2&>(m).f() and cout << static_cast<B&>(m).f() is 33, not 21?

struct B {
    virtual int f() {return 1;}
};
struct D1 : virtual public B {
    virtual int f(){return 2;}
};
struct D2 :  virtual public B{};
struct M : public D1, public D2 {
    virtual int f() {return 3;}
};

int main(){
    M m;
    cout << static_cast<D2&>(m).f();
    cout << static_cast<B&>(m).f();
    return 0;
}

Upvotes: 1

Views: 68

Answers (2)

Wyzard
Wyzard

Reputation: 34563

Your object is an instance of M, and casting to base reference types doesn't change that. The whole point of virtual functions is that when you call a function on a base pointer or reference, it goes to the derived implementation.

Upvotes: 2

Kerrek SB
Kerrek SB

Reputation: 477040

Because that's the entire point of virtual dispatch: The target of the dispatch is determined by the dynamic type of the most-derived object that contains the statically nominated object of the call expression.

If you don't want virtual dispatch, you can bypass it by qualifying the function call:

m.B::f();
m.D1::f();
m.D2::f();

Upvotes: 3

Related Questions