Showing posts with label polymorphism. Show all posts
Showing posts with label polymorphism. Show all posts

Thursday, October 6, 2016

Virtual Destructor :)

When We use Pointers In Inheritance then the destructor of derived class is not called.
To follow the normal rule we can use Virtual Destructor

Following is a simple program to Illustrate the Above Concept

#include<iostream>
using namespace std;
class A
{
public:
A()
{
cout<<"Base Constructor Called\n";
}
virtual ~A()
{
cout<<"Base Destructor Called\n";
}
};
class B:public A
{
public:
B()
{
cout<<"Derived Constructor Called\n";
}
virtual~B()
{
cout<<"Derived Destructor Called\n";
}
};
main()
{   A *p=new B();
delete(p);
}

Output:













And if we donot use virtual destructor then the above program gives the following output


Virtual Functions :)

As we  Know that the Polymorphism is the feature of OOP,which means we use the same name but multiple forms.
So in case of Run time Polymorphism the Virtual Functions Are used which tell about the binding of function procedure with its call at run time.
Virtual Functions done this by checking the object to which the pointer is pointing rather than the type of pointer.
Following is a Simple program to illustrate the above concept

#include<iostream>
using namespace std;
class Base
{
public:
void display()
{
cout<<"Display base\n";
}
virtual void show()
{
cout<<"Base Virtual\n";
}
};
class Derived:public Base
{
public:
void display()
{
cout<<"Display Derived\n"; }
    void show()
{
cout<<"Derived Virtual\n";
}
};
main()
{
Base b;
Derived d;
    Base *p=&b;
p->display();
p->show();
p=&d;
p->display();
p->show();
}

Output:



















So as we can see in the output the Display function of base class is called two times because it is not virtual
On the other hand the show function is called for both derived and base class because it is made virtual.