C++ Nelson Notes Unit 4
C++ Nelson Notes Unit 4
Syntax of Inheritance
class parent_class
};
1) Single inheritance
2) Multilevel inheritance
3) Multiple inheritance
4) Hierarchical inheritance
5) Hybrid inheritance
1. Single Inheritance
In single inheritance, a derived class can inherits the properties only from one base
class.
class base_class1
{
public:
base_class1()
{
cout<<"Constructor of Base class / Parent Class"<<endl;
}
};
Output:
Constructor of Constructor of base class / Parent Class
Constructor of Constructor of Derived class / Child Class
Multilevel Inheritance
In this type of inheritance, one class inherits the properties another child class.
From the below image, class B is derived from the base class A and the class C is
derived from the derived class B.
3) Multiple Inheritance
In Multiple Inheritance, a derived class can inherits the properties from multiple base
classes. For example: A class Bat is derived from bas classes Mammal and WingedAnimal.
It makes sense because bat is a mammal as well as a winged animal.
class Mammal
{
public:
Mammal()
{
cout << "Mammals can give direct birth." << endl;
}
};
class WingedAnimal
{
public:
WingedAnimal()
{
cout << "Winged animal can flap." << endl;
}
};
};
void main()
{
Bat b1;
}
Hierarchical Inheritance
If more than one class is inherited from the base class, it's known as hierarchical
inheritance.
In hierarchical inheritance, all features that are common in child classes are
included in the base class.
From the below image, first_derived_class, second_derived_class,
third_derived_class are derived from the base_class.
class A
{
public:
A()
{
cout<<"Constructor of A class"<<endl;
}
};
class B: public A
{
public:
B()
{
cout<<"Constructor of B class"<<endl;
}
};
class C: public A
{
public:
C()
{
cout<<"Constructor of C class"<<endl;
}
};
void main()
{
//Creating object of class C
C obj;
5) Hybrid Inheritance
Hybrid inheritance is a combination of more than one type of inheritance.
For example, A child and parent class relationship that follows multiple and
hierarchical inheritance both can be called hybrid inheritance.