Showing posts with label Crash. Show all posts
Showing posts with label Crash. Show all posts

20120123

Why destructor should be virtual in C++ ?

Why destructor should be virtual in C++ ?
Memory Leak ?

When delete is called virtual destructor makes sure to release memory of first derived class object then of by base class object. If destructor is not virtual then only the base class object's memory get released and not that of derived class object.
example:
#include<iostream>
using namespace std;
class base
{
  base(){};
 ~base(){};
};
class derived:public
{
  derived(){};
 ~derived(){};
};
int main()
{
base *ptr= new derived(); //exp1
delete ptr; //exp2
}
Explanation:
Line exp1 makes the derived and base constructoes to be called to allocate memory for base as well derived class objects.
But, if destructor is not virtual in base class then
Line exp2 makes to call the base destructor and derived destructor never gets called and hence memory allocated to derived class object is not release and leads to memory leak because memory used by derived class object can not be used util the end of the program.
Simples Way to learn Data Structure in C++ CPP or C
C++ Program for Circular Queue implementation using linked list
 
C++ program for Circular Queue implementation using Array

C++ program for reversing single Linked list nodes 

C++ Program for sorted single linked list with class

C++ Program for BST-Binary Search Tree   


Previous                             Home                               Next