Inheritance in C++
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.
NOTE: All members of a class except Private, are inherited
Purpose of Inheritance in C++
- Code Reusability
- Method Overriding (Hence, Runtime Polymorphism.)
- Use of Virtual Keyword
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 atleast 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, privtate or protected.
Example of Inheritance
Whenever we want to use something from an existing class in a new class, we can use the concept on Inheritace. Here is a simple example,
class Animal
{
public:
int legs = 4;
};
// Dog class inheriting Animal class
class Dog : public Animal
{
public:
int tail = 1;
};
int main()
{
Dog d;
cout << d.legs;
cout << d.tail;
}
4 1
Access Modifiers and Inheritance: Visibility of Class Members
Depending on Access modifier used while inheritance, the availability of class members of Super class in the sub class changes. It can either be private, protected or public.
1) Public Inheritance
This is the most used inheritance mode. In this the protected member of super class becomes protected members of sub class and public becomes public.
class Subclass : public Superclass
2) Private Inheritance
In private mode, the protected and public members of super class become private members of derived class.
class Subclass : Superclass // By default its private inheritance
3) Protected Inheritance
In protected mode, the public and protected members of Super class becomes protected members of Sub class.
class subclass : protected Superclass
Table showing all the Visibility Modes
| Derived Class | Derived Class | Derived Class |
Base class | Public Mode | Private Mode | Protected Mode |
Private |
Not Inherited |
Not Inherited |
Not Inherited |
Protected |
Protected |
Private |
Protected |
Public |
Public |
Private |
Protected |