#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.
To call
print()successfully on aCobject, you need to create and point to aCobject: