#include <iostream>
usingnamespace std;
class shape{public:virtualvoid f1(){} };//~ shape ends
class rectangle : publicvirtual shape
{
int a;
public:
rectangle(int b)
{
a=b;
}
int tell(){
cout<<"\nValue of A: "<<a;
return 0 ;
}
};//~ rectangle ends
class circle : publicvirtual shape
{
public :
void cast(rectangle &temp)
{
cout<<temp.tell();
}
void f1(){}
};
void main()
{
shape* obj1 = new rectangle(5);
rectangle* obj2 = dynamic_cast<rectangle*> (obj1);
circle* obj3 = dynamic_cast<circle*> (obj1);
obj2->tell();
obj3->cast(*obj2); //is working fine
obj2->f1();
obj3->f1(); //Giving run time error
}
In the above code i am getting run time error. obj3 is a null pointer but still line obj3->cast(*obj2) gets executed and at line obj3->f1() it throw error.
obj1 does not point to a circle, it points to rectangle. Therefore this is a bad cast. Therefore 'obj3' is a null pointer.
obj3->cast(*obj2); //is working fine
This works fine because the "cast" function doesn't use the 'this' pointer at all. Therefore it doesn't matter if 'this' is null (which it would be, because obj3 is null).
obj3->f1(); //Giving run time error
This doesn't work because f1 DOES use the this pointer (because it's virtual, it needs to look up the object's vtable). Since obj3 is a null pointer, it has no vtable, hence the runtime error.
When using dynamic cast to cast a pointer, you should always check to make sure the cast was successful:
1 2 3 4 5 6 7 8 9
circle* obj3 = dynamic_cast<circle*>(obj1);
if(obj3)
{
// cast was okay! go ahead and use obj3
}
else
{
// bad cast. Don't use obj3
}