C++ Inheritance
C++ Inheritance
The concept of reusability in C++ is supported using inheritance. We can reuse the properties of an existing class by inheriting it and deriving its properties. The existing class is called the base class and the new class which is inherited from the base class is called the derived class.
Syntax for Inheriting a Class
// Derived Class syntax
class derived_class_name : access_modifier base_class_name
{
// body of the derived class
}
Types of Inheritance in C++
1. Single Inheritance
Single inheritance is a type of inheritance in which a derived class is inherited with only one base class.
class ClassA
{
//body of ClassA
};
//derived from ClassA
class ClassB : public ClassA
{
//body of ClassB
};
2. Multiple Inheritance
Multiple inheritance is a type of inheritance in which one derived class is inherited from more than one base class.
class ClassA
{
//body of ClassA
};
class ClassB
{
//body of ClassB
};
//derived from ClassB and Class C
class ClassC : public ClassA, public ClassB
{
//body of ClassC
};
3. Hierarchical Inheritance
Hierarchical inheritance is a type of inheritance in which several derived classes are inherited from a single base class.
class ClassA
{
//body of ClassA
};
//derived from ClassA
class ClassB : public ClassA
{
//body of ClassB
};
//derived from ClassA
class ClassC : public ClassA
{
//body of ClassC
};
4. Multilevel Inheritance
Multilevel inheritance is a type of inheritance in which one derived class is inherited from another derived class.
class ClassA
{
//body of ClassA
};
//derived from ClassA
class ClassB : public ClassA
{
//body of ClassB
};
//derived from ClassB
class ClassC : public ClassB
{
//body of ClassC
};
5. Hybrid Inheritance
Hybrid inheritance is a combination of different types of inheritances.
class ClassA
{
//body of ClassA
};
class ClassB
{
//body of ClassB
};
//derived from ClassA and ClassA
class ClassC : public ClassA, public ClassB
{
//body of ClassC
};
//derived from ClassC
class ClassD : public ClassC
{
//body of ClassD
};