0

I am trying to understand why static_cast works different when it is performed on object than when it is performed on a pointer to object.

class A
{
    int myA;
public:
    A() { myA = 11; };
    virtual void Do() {  printf("\n A class is executed "); }
};
class B : public A
{
    int myB;
public:
    B(){ myB = 22; }

    void Do() {   printf("\n B class is executed "); }
};

When the following cast is performed, A::Do() is executed. Why? Why B's virtual table is neglected?

A t_a;
B t_b;
(static_cast<A>(t_b)).Do();  //output: A class is executed

But when it is done via pointer, B::Do() is executed.

A* pA = new B;
pA->Do();
(static_cast<A*>(pA))->Do();   //output: B class is executed

Can you give me a full explanation (including memory layout) to understand the difference.

RRR
  • 73
  • 4

0 Answers0