What are the advantages and disadvantages of inheritance

Follow by Email
Facebook0
Facebook
Google+
https://codingsec.net/2016/10/advantages-disadvantages-inheritance-2/

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.

When a base class and sub class contains a function with the same signature, and the function is called with base class object, then the function in derived class executes and the function in base class is said to be overridden. This is known as function overriding. Following program demonstrates function overriding:

#include
using namespace std;
class A
{
	protected:
		int x;
	public:
		void show()
		{
			cout<<"x = "<<x<<endl; } }; class B : public A { protected: int y; public: B(int x, int y) { this->x = x;
			this->y = y;
		}
		void show()
		{
			cout<<"x = "<<x<<endl;
			cout<<"y = "<<y<<endl;
		}
};
int main()
{
	A objA;
	B objB(30, 20);
	objB.show();
	return 0;
}

Output for the above program is:

x = 30
y = 20

In the above program, both super class A and sub class B contains the same function show() with same signature (function name plus parameters). So, when sub class object is used to call show(),function in sub class B executes overriding the function in super class A.

We know that when a base class pointer refers to a derived class object, the extra features in derived class are not available. To access the extra features in the derived class, we make the functions in the base class as virtual.

Take your time to comment on this article.

Follow by Email
Facebook0
Facebook
Google+
https://codingsec.net/2016/10/advantages-disadvantages-inheritance-2/

One Response

  1. priya 2017-12-15 Reply

Add a Comment

Your email address will not be published. Required fields are marked *

Like the article? please consider sharing it. Thank you

Advertisment ad adsense adlogger