Inheritance In C++

Inheritance is a very important concept of reusability of codes in C++.

Why inheritance?

In C++, if you have already made a class with many data members and member functions and now you want to re-use them in a new class, (without inheritance) you have to write each and every thing in that new class, but if we use the concept of inheritance, you can re-use the already made class in any other class.

Let me show you a practical example:

class animal

{

protected:

int teeth,legs;

};

It is class animal, that have two data member teeth and legs. We declared teeth and legs because any animal class which will be inherit from this class would must have teeth or legs.

class dog : public animal

{

public:

void bark()

{

teeth=32;

}

void eat();

}

We inherited animal class in dog class means now class dog can use the data members of class animals. We declared bark function in dog because dog can bark. We can inherit as many classes from animal class.

How to inherit a class?

The class in which you have to inherit is known as derived class and the class from which you want to inherit is known as base class.

Syntax:

class <derived-class name> : public/private/protected <base-class name>

I shown you one example above the syntax.

I will tell you what is referred from public/private/protected in my next post, so ignore it now.

Where in the practical world you can find the use of inheritance?

The best example of inheritance in practical world can be seen in Android Studio. Many classes with functionalities are already written and included in the program and the users just have to call and inherit them in there application!

So in this way and like this, the concept of inheritance is use for reusability of code.

You will see in detail the types of inheritance available in C++ and also about the access specifiers we kept before the base class in next posts.

Published by Yash Kukreja

I am more than a proGrammer();

Leave a comment

Design a site like this with WordPress.com
Get started