Regarding deleting a base ptr which is pointings to derived object.

R

Rajya

Deleting an pointer of type base class which is holding address of
derived class object gave out segemenation falut. I am using virtual
destructor. Code is somethg like this:

class base
{
public:
base()
{
cout<<"base const"<<endl;
}
virtual ~base()
{
cout<<"base dest"<<endl;
}
};
class derived : public base
{
derived()
{
cout<<"derived consts"<<end;
}
~derived()
{
cout<<"derived dest"<<endl;
}
};

int main()
{
base *Bptr;
derived Dobj;
Bptr = &Dobj;
cout<<"in main"<<endl;
delete Bobj;
}

OUTPUT:
base consts
derived consts
in main
derived dests
base dests
segamentation fault------- why is the fault . Can anyone explain me
this.
Thanks in Advance!
 
T

tonydee

int main()
{
        base *Bptr;
         derived Dobj;
         Bptr = &Dobj;
        cout<<"in main"<<endl;
         delete Bobj;
}

OUTPUT: ....
segamentation fault------- why is the fault . Can anyone explain me
this.

You only need to delete an object if you've allocated it on the heap
(with new).

Cheers,
Tony
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,770
Messages
2,569,583
Members
45,075
Latest member
MakersCBDBloodSupport

Latest Threads

Top