Introduction
In this post, I am going to write a program for addition of two numbers using single inheritance in c++.
Also Read: Tokens in C++ Programming
Inheritance is nothing but a mechanism of inheriting properties of one class into another class. Parent class / Base class is the class from which child class or derived class is formed. That means child class extends properties of base class. There are five types of inheritance in c++ programming and they are
- Single Inheritance
- Multilevel Inheritance
- Hierarchical Inheritance
- Multiple Inheritance
- Hybrid Inheritance
In this post, I am just writing a program using single inheritance only.
Single Inheritance in C++
In this type of inheritance, there is only one base class and one sub class. I hope you have understood what exactly single inheritance is.
Also Read: Best 5 Basic C++ Programs For Beginners
Now, let us see the actual c++ program.
Addition of Two Numbers Using Single Inheritance in C++
#include <iostream> using namespace std; class base { public: int a; void get_a() { cout<<"Enter the value of a: "<<endl; cin>>a; } }; class sub : public base { int b; public: void get_b() { cout<<"Enter the value of b: "<<endl; cin>>b; } void display() { cout<<"Addition of "<<a<<" and "<<b<<" is "<<(a+b); } }; int main() { sub s; s.get_a(); s.get_b(); s.display(); return 0; }
In the above program, I have created two classes, namely class base and class sub. Class base is a base class and class sub is a sub class. Properties of base is class is inherited to the class sub.
In the base class, there is only one variable i.e. a and one function i.e. get_a(). We can access these member variable and member function using the object of the class base.
Also Read: A Simple C++ Program
Similarly, in the class sub, there is also a member variable of class sub is b and member function of this class is get_b(). We can access these members using the object of the class sub only.
But, here we have used single inheritance and properties of class base is now the properties of the class sub. That means, object of class sub can access public members of class base.
In the main function, I have created the object of sub class and have accessed both the members of class base and class sub.
Also Read: Simple Interest Program in C++ using Class
See the following output.
Output

I hope you have understood the above program. If you have any difficulties, then please feel free to contact me. Thank you.