Add two numbers using single inheritance

Q. Write a C++ program to add two numbers using single inheritance. Accept these two numbers from the user in base class and display the sum of these two numbers in derived class.

Answer:

  • Inheritance is the most important concept of object oriented programming.
  • Deriving a class from another class is known as Inheritance.
Following program is demonstrating single inheritance.

#include<iostream>
using namespace std;

class AddData          //Base Class
{
        protected:
                int num1, num2;
        public:
                void accept()
                {
                        cout<<"\n Enter First Number : ";
                        cin>>num1;
                        cout<<"\n Enter Second Number : ";
                        cin>>num2;
                }
};
class Addition: public AddData   //Class Addition – Derived Class
{
                int sum;
        public:
                void add()
                {
                        sum = num1 + num2;
                }
                void display()
                {
                        cout<<"\n Addition of Two Numbers : "<<sum;
                }
};
int main()
{
        Addition a;
        a.accept();
        a.add();
        a.display();
        return 0;
}


Output:

single inheritance addition

Explanation :

In the above program, the base class AddData has two protected member variables namely num1 and num2. Class Addition is derived from the base class AddData.

The members of the base class are available in the derived class. This concept of accessing the members of the base class is called as Code Reusability.