getting run time error while usuing dynamic_cast

Hi,

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
#include <iostream>

using namespace std;

class shape{public:virtual void f1(){} };//~ shape ends


class rectangle : public virtual shape
{
	int a;
public:
	rectangle(int b)
	{
          a=b;
	}
	int tell(){
		cout<<"\nValue of A:    "<<a;
		return 0 ;
	}
};//~ rectangle ends

class circle : public virtual 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.

Kindly explain.
circle* obj3 = dynamic_cast<circle*> (obj1);

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
}
Thanks Disch!!
I got it..
Topic archived. No new replies allowed.