You could have done this yourself. I gave instructions. Lazy!
Code:
#include <iostream>
using namespace std;
class base
{
public:
virtual void func() const = 0;
};
class real_derive_a : public base
{
public:
real_derive_a(){}
virtual void func() const {cout << "real_derive_a" << endl;}
};
class real_derive_b : public base
{
public:
real_derive_b(){}
virtual void func() const {cout << "real_derive_b" << endl;}
};
class imag_derive
{
public:
imag_derive(){}
virtual void func() const {cout << "imag_derive" << endl;}
};
int main()
{
base* pBase = new real_derive_a;
real_derive_b* pRealB;
pRealB = (real_derive_b*)pBase;
if(pRealB == 0)
cout << "C style cast failure" << endl;
else
pRealB->func(); // function executes but cast fails. Which function would this have called if cast didnt fail?
pRealB = dynamic_cast<real_derive_b*>(pBase);
if(pRealB == 0)
cout << "dynamic cast failure" << endl;
else
pRealB->func();
imag_derive* pImag;
pImag = (imag_derive*)pBase;
if(pImag == 0)
cout << "C style cast failure" << endl;
else
pImag->func(); // same here.
pImag = dynamic_cast<imag_derive*>(pBase);
if(pImag == 0)
cout << "dynamic cast failure" << endl;
else
pImag->func();
delete pBase;
return 0;
}