What is a inheritance in C++?
INHERITANCE
(Concept)
- Existing class are main components of inheritance
- New classes can be derived from existing class
- The properties of existing class are simply extended to new class
- The new class created using such methods are called as derived class and the existing classes are known as base classes. The relationship between new class and existing class are known as kind of relationship.
- The programmer can define new member variables and functions in derived class but the base class remain unchanged.
- The object of derived class can access members of base class as well as derived class. On the other hand the base class cannot access members of derived class. The base classes do not know about their sub classes.
#include<iostream.h>#include<conio.h> class A { public : int X; }; class B : private A { public :int Y;B() { X=20;Y=40; }
void show() {
cout<<“X=“<<X;
cout<<“Y=“<<Y;
}
};
void main() {
clrscr();
B b;
b.show();
}
OUTPUT
X=20
Y=40
Explanation: class B is a derived class from class A. The member variable X is a public member of base class. The object b of derived class cannot access variable x directly.b.X// cannot accessMember function of derived class can access members of base class. i.e the function show() does the same.
Why??The member functions of derived class cannot access the private member variables of base class. The private members of base class can be accessed using public member functions of same class. This approach makes a program lengthy. To overcome the problem associated with private data another access specifier called protected was introduced.
Q) Write a program to declare protected data in base class. Access data of base class declared under protected section using member functions of derived class.
The process of inheritance depends on (1)number of base classes (i.e program can use one or more base class to derive a single class)
(2)Nested derivation (the derived class can be used as base class and new class can be derived from it.
Different types of inheritance are:
- Single
- Multiple
- Hierarchical
- Multilevel
- Hybrid
- Multipath
When only one base class is used for derivation of a class and derived class is not used as base class, such type of inheritance between one base and derived class is known as single inheritance.
When two or more base classes is used for derivation of a class, it is called multiple inheritance.
When a single base class is used for derivation of two or more classes.
When a derived class is derived from another derived class i.e, derived class acts as base class.
When a class is derived from another class i.e derived class acts as base class such type of inheritance is called multilevel inheritance.
Hybrid inheritance
Combination of one or more type of inheritance is called as hybrid inheritance.
Thanks for visiting our website 🙏