Written by Sai Sandeep Thota on March 13, 2013 in C++ > Programming

What is Inheritance?

GET ALERTS:

Get our Latest updates delivered to your mailbox!

C++ strongly supports the concept of reusability. If we have written a class earlier, C++ allows us to reuse the class again. It is basically done by creating a new class and reusing the properties of the existing classes. So what is Inheritance? The mechanism of deriving a new class from an existing class is called as Inheritance and it is one of the greatest qualities. The existing class is referred as base class and the new class is referred as derived class.

There are 5 types of inheritances in C++:

  1. Single Inheritance
  2. Multilevel Inheritance
  3. Multiple Inheritance
  4. Hierarchical Inheritance
  5. Hybrid Inheritance

When a class inherits another class the members of the base class become members of the derived class. The access status of the base-class  access specifier must be either public, private or protected. If no access specifier is present, the access specifier is private by default if the derived class is a class.

Base class members behavior:
private: we can access them only within the class.
protected: we can access them within the class + derived class.
public: we can access them within the class + derived class + main program.

If derived class can access base class in public then all the protected members in base class will be protected in derived and all the public members in the base will become public in derived class and private class will remain unchanged.

Single Inheritance

Lets discuss about Single Inheritance in this article and later dig into other four types of inheritances. In Single Inheritance a derived class will contain only one base class.
single_inheritance

Single Inheritance Program

#include<conio.h>
#include<iostream.h>

class base {
	public:
	int i, j;
	void set(int a, int b) {
		i=a; j=b;
	}
	void show() {
		cout<<"\nValues are i="<<i<<" j="<<j;
		cout<<"\nMultiplication i*j="<<i*j;
	}
};

class derived : public base {
	public:
	int k;
	derived(int x) {
		k=x;
	}
	showk() {
		cout<<"\nk="<<k;
		return 0;
	}
};

void main() {
	derived ob(5);
	clrscr();
	ob.set(5,6);
	ob.show();
	ob.showk();
	getch();
}

Output:single_inheritance_program

{ 0 comments… add one now }

Leave a Comment

Previous post:

Next post: