Inheritance allows hierarchical classification of objects by allowing new classes to acquire properties from older base classes. This allows for code sharing and reuse, which increases reliability and decreases maintenance costs. There are different types of inheritance like single, multilevel, multiple, and hierarchical. Inheritance is implemented using the derived class and base class syntax where the derived class inherits visibility of members defined in the base class depending on the visibility mode being private, protected, or public. Virtual inheritance solves issues like ambiguous function calls and duplication of data members that can occur with multiple inheritance.
2. Inheritance
• One of the Major pillars of OOP approach.
• Process by which one object acquires properties
of another.
• New classes to be built from older one.
• ‘IS A’ relationship
• Ex: Parent
Parent Features Base Class
Parent
Features
Child Child Derived Class
Features
4. Benefits
• Reusable code, reliability and decreased
maintenance cost.
• Code Sharing: software level and class level
• Extension: Construction of new system from old
components: focus on new and unusual parts
of system
5. Types of Inheritance in C++
A
A
B C D
B
(D) Hierarchical
(a) Single A B
A
A
C
B (C) Multiple B C
C
D
(b) Multilevel (E) Hybrid
6. Syntax
class derived-class-name : visibility mode
base class-name
{
...//
...// members of derived class
...//
};
egg.
Class ABC : private XYZ
{
members of ABC
};
7. Visibility Modes
Base Class Derived Class Derived Class
Visibility: Visibility:
Visibility
Public Private
Derivation Derivation
private Not inherited Not inherited
protected protected private
public public private
8. A Example
class B //base class
{
protected:
int x; int y;
public:
B() { } //default constructor
void read()
{
cout<<“ Enter X of Class B :”; cin>>x;
cout<<“ Enter Y of Class B :”; cin>>y;
}
void show()
{
cout<<“ X in class B:” << x <<endl;
cout<<“ y in class B:” << y <<endl;
9. class D: public B //derived class
{
protected:
int y, int z;
public:
D() { } //default constructor
void read()
{
B :: read(); //read base class data first
cout<<“ Enter Y of Class D :”; cin>>y;
cout<<“ Enter Z of Class D :”; cin>>z;
}
void show()
{
B :: show(); //display base class data
cout<<“ X in class B:” << x <<endl;
cout<<“ y in class B:” << y <<endl;
10. void main()
{
D d; //obj of derived
cout<< “Enter data for object of class D ..” <<endl;
d.read();
cout<< “Contents of object of class D ..” <<endl;
d.show();
}
--------------------------------------------------------------
if input given is 1 2 3 4 op will be
Contents of object of class D ..
X in class B : 1
Y in class B : 2
Y in class D : 3
Z in class D : 4
Y of B, show from D = 2
11. Virtual Inheritance
Problems with Multiple Inheritance:
1.Ambiguos Function call
2.Duplication of Data Members
Solution
Use virtual keyword
class A {};
class B: virtual public A{};
class C: virtual public A{};
Class D: public B, public C {};