C++ allows programmers to create virtual destructors. But, it doesn’t allow virtual constructors to be created because of various reasons. To know why a virtual destructor is needed, consider the following program:
#include <iostream>
using namespace std;
class A
{
public:
A()
{
cout<<“A’s constructor”<<endl;
}
~A()
{
cout<<“A’s destructor”<<endl;
}
};
class B : public A
{
public:
B()
{
cout<<“B’s constructor”<<endl;
}
~B()
{
cout<<“B’s destructor”<<endl;
}
};
int main()
{
A *bptr = new B();
delete bptr;
return 0;
}
Output for the above program is as follows:
A‘s constructor
B’s constructor
A‘s destructor
From the above output you can see that derived class destructor didn’t execute. This might lead to problems like memory leakage. To avoid such problems we make destructor in base class as virtual destructor.
Virtual destructor instructor ensures that the derived class destructor is executed. To create a virtual destructor, precede the destructor definition with virtualkeyword. Following program demonstrates a virtual destructor:
#include <iostream>
using namespace std;
class A
{
public:
A()
{
cout<<“A’s constructor”<<endl;
}
virtual ~A()
{
cout<<“A’s destructor”<<endl;
}
};
class B : public A
{
public:
B()
{
cout<<“B’s constructor”<<endl;
}
~B()
{
cout<<“B’s destructor”<<endl;
}
};
int main()
{
A *bptr = new B();
delete bptr;
return 0;
}
Output for the above program is as follows:
A‘s constructor
B’s constructor
B‘s destructor
A’s destructor
Now you can see that derived class constructor is also executed.
Advantages and Disadvantages of Inheritance
Advantages of inheritance are as follows:
Inheritance promotes reusability. When a class inherits or derives another class, it can access all the functionality of inherited class.Reusability enhanced reliability. The base class code will be already tested and debugged.As the existing code is reused, it leads to less development and maintenance costs.Inheritance makes the sub classes follow a standard interface.Inheritance helps to reduce code redundancy and supports code extensibility.Inheritance facilitates creation of class libraries.
Disadvantages of inheritance are as follows:
Inherited functions work slower than normal function as there is indirection.Improper use of inheritance may lead to wrong solutions.Often, data members in the base class are left unused which may lead to memory wastage.Inheritance increases the coupling between base class and derived class. A change in base class will affect all the child classes.
Take your time to comment on this article.
No comments:
Post a Comment