Pointer to subclass call correct virtual function

72 Views Asked by At
#include <iostream>

class A {
public:
  virtual void print() { std::cout << "class A" << std::endl; }
};

class B : public A {
public:
  virtual void print() override { std::cout << "class B" << std::endl; }
};

class C : public A {
public:
  virtual void print() override { std::cout << "class C" << std::endl; }
};

int main() {
  B obj1;

  A *ptr1 = dynamic_cast<A *>(&obj1);
  ptr1->print();

  B *ptr2 = dynamic_cast<B *>(ptr1);
  ptr2->print();

  C *ptr3 = dynamic_cast<C *>(ptr2);
  ptr3->print();
}

Based on my understanding, when we call virtual function of an object using pointer, it would search the virtual table of the object and call the matching function for us.

But when I tried to run the code above, it only print two "class B" (the first two calls).

And looks like the third print on ptr3 will terminate the program, can someone tell me why the third print() is failed.

1

There are 1 best solutions below

0
Shehzad Hussain On

To call print() successfully on a C object, you need to create and point to a C object:

C obj2;
C *ptr3 = dynamic_cast<C *>(&obj2);
ptr3->print(); // This will now print "class C"