Showing posts with label virtual destructor. Show all posts
Showing posts with label virtual destructor. Show all posts

20130330

How to see vtable virtual table for virtual functions in cpp


Virtual table is look up table for virtual functions. It contains the function pointer to the virtual functions. Virtual table is created for each class having one or more virtual function and classes derived from that class.virtual pointer better known as vptr containing the address of vtable is created for the most base class thats why size of empty class with virtual function is equal to the size of a pointer(8 bytes for a 64 bit computer)while size of a empty class without any virtual functions is only one byte.
Command to see vtable/virtual table of a class.
Here if the name of the program is "classWithVf.cxx" so the command to see the vtable of the class is:

g++ -fdump-class-hierarchy classWithVf.cxx


#include<iostream>
using namespace std;

class M //empty class
{
public:
void f() {}
};
class A //empty class
{

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