Why would you make a destructor virtual?

Answer Posted / chandra sekhar

what chandra said is correct.but it is not 100% correct.for
that answer i want to add one point.

whenever
1)there is a pointer in the base class and we allocated
with the help of new in base class and anthoer pointer in
derived class and agin we allocated with the help of new.
2)whenever the base class object pointer points to
derived class object,and is being created using new.
i.e class base - base class
in main - base bptr;
class derived - derived class
in main - bptr = new derived();

this will be illustrated with an example given below


#include <iostream.h>
class Base
{ protected:
int *ptr;
public:
Base()
{ ptr = new int[10];
cout<<"Constructor: Base"<<endl;
}
virtual ~Base()
{
cout<<"Destructor : Base"<<endl;
delete []ptr;
}
};
class Derived: public Base
{
protected:
int *ptr1;
public:
Derived()
{
ptr1=new int[10];
cout<<"Constructor: Derived"<<endl;
}
~Derived()
{
delete []ptr1;
cout<<"Destructor : Derived"<<endl;
}
};
void main()
{
Base *Var = new Derived;
delete Var;
}

if we are not placing virtual in base class, only base
class destructor will be called because "var is of type
Base".so,
if we are not placing virtual compiler will see only "type
of the pointer,not the object which it is holding".so,if we
place virtual it will see the object it is holding.

now memory allocated for ptr,ptr1 in heap was destroyed by
destructors of the respective class.

Is This Answer Correct ?    4 Yes 0 No



Post New Answer       View All Answers


Please Help Members By Posting Answers For Below Questions

There are 100 students in a class. The management keep information in two tables. Those two tables are given like Roll no Name Age 001 ABC 15 002 XYZ 14 and Roll No Subject Marks 001 Math 75 001 Physics 55 002 Math 68 001 Hindi 69 They want the information like this Roll No Name Hindi Physics Math Total 001 ABC 69 55 75 199 002 XYZ 68 74 84 226 And Roll No Suject Highest 001 Math 98 007 Physics 84 021 Hindi 74 All 275 All information is kept in structure in main memory. You have to find last two tables.

2538


Is java based off c++?

536


the maximum length of a character constant can be a) 2 b) 1 c) 8

602


Can you please explain the difference between overloading and overriding?

604


What is flush programming?

578






Write a short code using c++ to print out all odd number from 1 to 100 using a for loop

590


List the merits and demerits of declaring a nested class in C++?

612


What is atoi?

547


Why we use #include iostream in c++?

585


Explain the differences between list x; & list x();.

608


Define stacks. Provide an example where they are useful.

583


What does n mean in c++?

634


What is c++ mutable?

708


What do you mean by global variables?

574


Is it legal in c++ to overload operator++ so that it decrements a value in your class?

616