Static_cast and virtual methods in c++

445 views Asked by At

in the following code, due to name() being virtual, I would expect that the method of derived struct will be called. Conversely, whats get written out is "A". Why?

#include <iostream>
using namespace std;
struct A {
    virtual string name() { return "A"; }
};
struct B : A {
    string name() { return "B"; }
};
int main (int argc, char *argv[]) {
    B b;
    cout << static_cast<A>(b).name() << endl;
    return 0;
}
3

There are 3 answers

0
Anton Savin On BEST ANSWER

static_cast<A>(b) creates a temporary variable of type A constructed from b. So calling name() indeed invokes A::name().

In order to observe polymorphic behavior you may do

static_cast<A&>(b).name()
1
Steephen On

As oliver Charlesworth mentioned in comment, you need pointer or refernce of the object required to see the impact of polymorphism. Then system will identify the dynamic type of the object and invoke the corresponding function. How you can invoke polymorphism using reference is explained in Anton Savin's answer.

For the expected result if you want to use pointer, you have to do as follows in main:

A *a= new B();
cout << a->name() << endl;
0
Christopher Oezbek On

What you are experiencing is called slicing. Essentially the static cast will cut the B part away from the object and you keep just an A.

What is object slicing?