Binary Operator Example using Operator Overloading in C++


This program defines a class Box which has three private data members: length, breadth, and height, along with several member functions. The member function Volume() calculates the volume of the box and returns it. The member functions Length(), Breadth(), and Height() set the values of length, breadth, and height, respectively. The operator+ overload function overloads the + operator to add two Box objects and return the resulting Box object.

In main(), three Box objects are defined: Box1, Box2, and Box3. The dimensions of Box1 and Box2 are set using the Length(), Breadth(), and Height() member functions. The volumes of Box1 and Box2 are then calculated using the Volume() member function and printed to the console. Finally, Box1 and Box2 are added together using the overloaded + operator, and the volume of the resulting Box3 is calculated and printed to the console.

Source Code

#include<iostream>
using namespace std;
class Box
{
   public:
    float Volume(void)
    {
       return length*breadth*height;
    }
    void Length(float l )
    {
       length=l;
    }
    void Breadth(float b)
    {
       breadth=b;
    }
    void Height(float h)
    {
        height=h;
    }
    Box operator+(const Box& b)
    {
       Box box;
       box.length = this->length + b.length;
       box.breadth = this->breadth + b.breadth;
       box.height = this->height + b.height;
       return box;
    }
   private:
        float length;
        float breadth;
        float height;
};
int main()
{
   Box Box1;
   Box Box2;
   Box Box3;
   float volume = 0.0;
   Box1.Length(6.0);
   Box1.Breadth(7.0);
   Box1.Height(5.0);
   Box2.Length(12.0);
   Box2.Breadth(13.0);
   Box2.Height(10.0);
   volume = Box1.Volume();
   cout<<"Volume of Box1 : "<<volume<<endl;
   volume = Box2.Volume();
   cout<<"Volume of Box2 : "<<volume<<endl;
   Box3 = Box1 + Box2;
   volume = Box3.Volume();
   cout<<"Volume of Box3 : "<<volume<<endl;
   return 0;
}
To download raw file Click Here

Output

Volume of Box1 : 210
Volume of Box2 : 1560
Volume of Box3 : 5400

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