Inheritance
Inheritance
Inheritance is a process in which one object acquires all the properties and behaviors of
its parent object automatically. In such way, you can reuse, extend or modify the
attributes and behaviors which are defined in other class.
The class which inherits the members of another class is called derived class and the
class whose members are inherited is called base class. The derived class is the
specialized class for the base class.
Sub Class: The class that inherits properties from another class is called Sub class or
Derived Class.
Super Class: The class whose properties are inherited by sub class is called Base
Class or Super class.
Code reusability: Now you can reuse the members of your parent class. So, there is
no need to define the member again. So less code is required in the class.
Visibility modes can be classified into three categories:
o Public: When the member is declared as public, it is accessible to all the
functions of the program.
o Private: When the member is declared as private, it is accessible within the class
only.
o Protected: When the member is declared as protected, it is accessible within its
own class as well as the class immediately derived from it.
class A
{
public:
int x;
protected:
int y;
private:
int z;
};
class B : public A
{
// x is public
// y is protected
// z is not accessible from B
};
class C : protected A
{
// x is protected
// y is protected
// z is not accessible from C
};
Types of Inheritance
o Single inheritance
o Multiple inheritance
o Hierarchical inheritance
o Multilevel inheritance
o Hybrid inheritance
Single Inheritance
When one class inherits another class which is further inherited by another class, it is
known as multi level inheritance in C++. Inheritance is transitive so the last derived
class acquires all the members of all its base classes.
Multiple Inheritance
Multiple inheritance is the process of deriving a new class that inherits the attributes
from two or more classes.
class A
{
// body of the class A.
}
class B : public A
{
// body of class B.
}
class C : public A
{
// body of class C.
}
class D : public A
{
// body of class D.
}
Hybrid Inheritance
Hybrid inheritance is a combination of more than one type of inheritance.