Hi Folks :),
I need your help:?:, I am getting segmentation fault for "delete bptr_1" ( please refer program written below and line number 46 ).
If i remove statements "delete dptr;" (@line 32) inside try{}, then the program executes otherwise it will give error.
Could you please tell me why shouldnot i delete "dptr" inside try{}
Does delete dptr inside try{} deletes bptr_1 too?
#include<iostream>
using namespace std;
class base
{
public:
virtual ~base()
{ }
};
class derived: public base
{
public:
~derived()
{ }
};
int main()
{
base *bptr_1 = new derived();
base *bptr_2 = new base();
derived *dptr;
try
{
dptr = dynamic_cast<derived*>(bptr_1);
if(dptr == 0)
cout<<"(1) base ptr1 not pointing to derived"<<endl;
delete dptr; // deleting memory allocated. If i remove this line,then program works
dptr = 0; // assigning the pointer to null, to reuse
dptr = dynamic_cast<derived*>(bptr_2);
if(dptr == 0)
cout<<"(2) bptr_2 not pointing to derived"<<endl;
}
catch (exception& err)
{
cout<<"error catched :"<<err.what()<<endl;
}
cout<<"delete base ptr pointing to d"<<endl;
delete bptr_1; //SEGFAULT HERE
cout<<"delete base ptr pointing to base"<<endl;
delete bptr_2;
cout<<"delete derived ptr"<<endl;
delete dptr;
return 0;
}
OUTPUT:
(2) bptr_2 not pointing to derived
delete base ptr pointing to d
Segmentation fault