0

I want to cast the data to class instance using static_cast. Strangely it always cast's to base class and not the sub class which is initialized. Here is the example code:

#include <iostream>
using namespace std;

class A
{
public:
    void Display () {
        fprintf(stderr, "I am A\n");
    }
};

class B : public  A
{
public:
    void Display () {
        fprintf(stderr, "I am B\n");
    }
};

int main()
{
    B *b=new B();
    b->Display(); //Invokes subclass function
    A *a=static_cast<A*>(b);
    a->Display(); //Invokes baseclass function
}

Current Output:

I am B
I am A

Expected Output:

I am B
I am B
Royal Pinto
  • 2,869
  • 8
  • 27
  • 39

0 Answers0