Explain the need for "Virtual Destructor"?

Answers were Sorted based on User's Feedback



Explain the need for "Virtual Destructor"?..

Answer / lylez00

If A is a base class, and from that, B is derived, and a
dynamically allocated object of type B is deleted via a
pointer of type A, then B's destructor will not be invoked
unless A's destructor is virtual.

A *a = new B();
delete a; // won't invoke B's destructor unless A's
destructor is virtual

Is This Answer Correct ?    12 Yes 3 No

Explain the need for "Virtual Destructor"?..

Answer / p govind rao

A destructor can be declare virtual. virtual destructor is
mainly useful during inheritance.

class base
{
public:
base(){}
virtual ~base(){}
};

class derv
{ char *p;
public :
derv(){ptr=nes char[2];}
~derv(){delete ptr;}

} ;

main()
{
base *baseptr=new derv();
delete baseptr;
}

If base class, and derived class, and a dynamically
allocated object of type derived is deleted via a pointer
of type base, then derived's destructor will not be invoked
unless base's destructor is virtual.

base *baseptr = new derv();
delete baseptr; // won't invoke B's destructor unless A's
destructor is virtual

Is This Answer Correct ?    6 Yes 0 No

Post New Answer

More C++ General Interview Questions

What are mutator methods in c++?

0 Answers  


difference between c and c++?

38 Answers   Cognizant, IBM, Infosys, Oracle, Sarva Shiksha Abhiyan, Wipro,


Can turbo c++ run c program?

0 Answers  


Q1 On the screen how do you write the following words? she sells seashells by the seashore (a) all in one line (b) in three lines Q2 Write a program that asks interactively the user’s name and age and responds with Hello name, next year you will be next_age. where next_age is age + 1 Q3 For the different values of n, what is the output? printf(“%x %c %o %d”,n,n,n,n); (a) n = 67 (b) n = 20 (c) n = 128 (d) n = 255 (e) n = 100 Q4 What will be the output of the following program? int main() { char a,b,c; scanf(“%c %c %c”,&a,&b,&c); printf(“a=%c b=%c c=%c”,a,b,c); return 0; } [Note: The user input is:ABC DEF GHI]

1 Answers  


Explain this pointer?

0 Answers  






Explain the concept of dynamic allocation of memory?

0 Answers  


Perform addition, multiplication, subtraction of 2-D array using Operator Overloading.

0 Answers   Nucleus, TCS,


What is c strings syntax?

0 Answers  


What about Virtual Destructor?

1 Answers   Virtusa,


What is the difference between public, private, and protected access?

0 Answers  


How does work in c++?

0 Answers  


What are the various operations performed on stack?

0 Answers  


Categories