Inheritance The mechanism of deriving a new class from the old class is known as inheritance Inheritance allows a class to acquire properties and behaviors of another class. Promotes code reusability and logical hierarchy.
Types of inheritances Single Inheritance Multilevel Inheritance Multiple Inheritance Hierarchical Inheritance Hybrid Inheritance
Multiple Inheritance Multiple Inheritance is a feature of C++ where a derivedclass can inherit from more than one base class. It's like having traits from both your parents! i.e one subclass is inherited from more than one base class.
Example code :
Example code :
Inheritance Ambiguity in C++ In multiple inheritances, when one class is derived from two or more base classes then there may be a possibility that the base classes have functions with the same name, and the derived class may not have functions with that name as those of its base classes. If the derived class object needs to access one of the similarly named member functions of the base classes then it results in ambiguity because the compiler gets confused about which base’s class member function should be called.
Code and output
Solution for ambiguity To solve this ambiguity scope resolution operator is used Syntax: objectname.classname :: functionname () ;
Corrected code:
Try writing code for this problems : Create a class printer and a class scanner. Then make a derived class all in one printer which inherits from both and demonstrates multiple inheritance. Create a class teacher and a class researcher. Then make a derived class professor which inherits from both and displays details.
Hierarchical Inheritance In hierarchical inheritance , more than one subclass is inherited from a single base class. It’s like a siblings in a family. i.e. more than one derived class is created from a single base class.
Example code :
Example code :
Try writing code for this problems : Create a base class shape with a derived class circle and square. In which Each derived class should display its type. Create a base class account with a derived class savingsaccount , currentaccount . Each should have its own constructor and a function to display account details. Demonstrate hierarchical inheritance.