Thursday, 22 April 2021

Inheritance in C++

 

Inheritance in C++




Introduction

 

One of the main advantages of object oriented programming is reusability. Using already existing code is known as reusability. C++ supports reusability through inheritance which is creating a new class from already existing class.

 

Inheritance is defined as deriving properties and behavior from one class to another class. The existing class from which properties and behavior are derived is known as a base class or super class. The new class into which the properties and behavior are derived is known as a derived class or sub class.

 

Inheritance is also known as is-a relationship between classes. For example a Employee is a Person and similarly Programmer is a Person. Common properties and behavior of Employee and Programmer will be available in Person class and specific properties and behavior are present in Employee and Programmer class. Inheritance or is-a relationship between a base class and derived class is represented as follows:

 

inheritance

 

Defining a derived class

Syntax for creating a derived class is as follows:

 

 

In the above syntax access-specifier is optional and the valid values for it are private, protected, or public. If access specifier is not provided, by default it is private mode.

 

Access Specifiers

 

In C++ there are three access specifiers: private, protected, and public. Let’s look at each one of them in detail.

 

private:

Private is the most restrictive access specifier. Class members which are declared as private cannot be accessed outside the class (except in friend classes and friend functions). In private derivation, protected and public members become private members in the derived class and cannot be inherited further.

 

protected:

Protected is less restrictive than private. Class members which are declared as protected are accessible only within the class and in the direct child classes of that class. In protected derivation, protected and public members of base class become protected members of derived class.

public:

Public is the least restrictive access specifier. Class members which declared as public are accessible from anywhere. In public derivation, protected and public members of base class become protected and public members of derived class respectively.


No comments:

Post a Comment

Inheritance in C++

  Inheritance in C++ Contents  1  Introduction 1.1  Defining a derived class 1.2  Access Specifiers 1.3  Constructors and Destructors in Inh...