Inheritance in C++
Inheritance is one of the object oriented concepts which deals with methods and attributes. It is the process of getting properties from base class to child class.
It has the following features.
Key terms:
Base class: it is foundation class which has methods
and attributes definition. It is also known as “Parent” class.
Derived class: it gets the details from base class. It
is called “Child” class.
The types of inheritance are given below.
Single: it has a base class and derived class.
Hierarchical: it deals with a base class with multiple
derived class.
Hybrid: it is a combination of all types.
Multiple: a single inherited class with multiple base
class.
Multilevel: it is a chain of
inheritance.(X->Y->Z).
Let us create a c++ program to display message using
inheritance:
This code creates a parent class with msg() function.
It derives a child class and creates a msgchild()
function.
‘main()’ function creates the objects for both classes
and call its member functions.
Program:
#include <iostream>
using namespace std;
class Parent {
public:
void msg() {
cout
<< "Hi,this is the message from parent class!" << endl;
}
};
class child : public Parent {
public:
void
msgchild() {
cout
<< "Hello, this is the message from the child class!" <<
endl;
}
};
int main()
{
Parent o1;
o1.msg();
child c1;
c1.msgchild();
}
Output:
Hi,this is the message from parent class!
Hello, this is the message from the child class!
Hope, this code is helpful to you. Inheritance always
utilises the code reusability. Keep coding!!!
Comments
Post a Comment