Below is code snippet,
#include <iostream>
using namespace std;
class A
{
public:
void print() const
{
cout << "In A::print()\n";
}
virtual void show()
{
cout << "In A::show()\n";
}
};
class B : public A
{
public:
void print() const
{
cout << "In B::print()\n";
}
void show()
{
cout << "In B::show()\n";
}
};
int main() {
A* a = new A;
a->show();
a->print();
B* b = dynamic_cast<B*>(a);
cout << b << endl;
b->print();
b->show();
return 0;
}
Here is output when I run this (I am using Visual c++ compiler),
In A::show()
In A::print()
00000000
In B::print()
and then program stops working ....
There are two questions,
1. Why/How call to function B::print()
is successful even after dynamic_cast
is failed since value of b
is 0 as seen in output?
- Why program stopped working when
B::show()
is called (given that call toB::print()
was successful in line before it)?