Addition Example using Multiple Inheritance in C++


This code defines three classes A, B, and C, where C is derived from both A and B. A contains a protected integer a and a public method get_a that sets the value of a. B contains a protected integer b and a public method get_b that sets the value of b.

C inherits from both A and B and contains a public method display. display outputs the values of a and b and then calculates and outputs their sum. In main, an instance of C is created, and the get_a and get_b methods are called to set the values of a and b, respectively. Then the display method is called to output the values and sum.

Source Code

#include<iostream>
using namespace std;
class A
{
   protected:
    int a;
   public:
    void get_a(int n)
    {
      a=n;
    }
};
class B
{
   protected:
    int b;
   public:
    void get_b(int n)
    {
      b=n;
    }
};
class C : public A,public B
{
  public:
    void display()
    {
      std::cout<<"The value of a is : "<<a<<std::endl;
      std::cout<<"The value of b is : "<<b<<std::endl;
      cout<<"Addition of a and b is : "<<a+b;
    }
};
int main()
{
  C c;
  c.get_a(10);
  c.get_b(20);
  c.display();
  return 0;
}
To download raw file Click Here

Output

The value of a is : 10
The value of b is : 20
Addition of a and b is : 30

Program List


Flow Control

IF Statement Examples


Switch Case


Goto Statement


Break and Continue


While Loop


Do While Loop


For Loop


Friend Function in C++


String Examples


Array Examples


Structure Examples


Structure & Pointer Examples


Structure & Functions Examples


Enumeration Examples


Template Examples


Functions


Inheritance Examples

Hierarchical Inheritance


Hybrid Inheritance


Multilevel Inheritance


Multiple Inheritance


Single Level Inheritance


Class and Objects

Constructor Example


Destructor Example


Operator Overloading Example


Operator and Function Example


List of Programs


Pointer Examples


Memory Management Examples


Pointers and Arrays


Virtual Function Examples