Header Ads Widget

Introduction to Inheritance in C++ Object Oriented Programming

 Introduction to inheritance


                    Inheritance is the capability of one class to acquire properties and characteristics from another class. The class whose properties are inherited by other class is called the Parent or Base or Super class. And, the class which inherits properties of other class is called Child or Derived or Sub class.

Inheritance makes the code reusable. When we inherit an existing class, all its methods and fields become available in the new class, hence code is reused.

Purpose of Inheritance

1) Code Reusability

2) Method Overriding (Hence, Runtime Polymorphism.)

3) Use of Virtual Keyword

Basic Concepts:

Basic Syntax of Inheritance

class Subclass_name: access_mode Superclass_name

While defining a subclass like this, the super class must be already defined or at least declared before the subclass declaration. Access Mode is used to specify, the mode in which the properties of superclass will be inherited into subclass, public, private or protected.

Example of Inheritance

class Animal

{ public:

int legs = 4;

};

class Dog : public Animal

{ public:

int tail = 1;

};

int main()

{

Dog d;

cout << d.legs;

cout << d.tail;

}

Output :      4 1