Assignment Operator Overloading Example in C++


This code defines a class Distance which represents a distance in feet and inches. It has two private data members feet and inches, and two constructors: a default constructor that sets both feet and inches to zero, and a parameterized constructor that takes two integer arguments for feet and inches. It also defines an overloaded assignment operator = that copies the values of the feet and inches data members from one Distance object to another.

In main(), two Distance objects D1 and D2 are created using the parameterized constructor. Their values are displayed using the displayDistance() method. Then, D1 is assigned the value of D2 using the = operator, and the new value of D1 is displayed using displayDistance() again. Overall, this code demonstrates how to overload the assignment operator in a class and use it to copy objects of the same class.

Source Code

#include<iostream>
using namespace std;
class Distance
{
   private:
     int feet;
     int inches;
   public:
      Distance()
      {
        feet=0;
        inches=0;
      }
      Distance(int f,int i)
      {
        feet=f;
        inches=i;
      }
      void operator =(const Distance &D)
      {
        feet=D.feet;
        inches=D.inches;
      }
      void displayDistance()
      {
        cout<<"F: "<<feet<<" I:"<<inches<<endl;
      }
};
int main()
{
   Distance D1(11,10),D2(5,11);
   cout<<"\nFirst Distance : ";
   D1.displayDistance();
   cout<<"\nSecond Distance :";
   D2.displayDistance();
   D1=D2;
   cout<<"\nFirst Distance :";
   D1.displayDistance();
   return 0;
}
To download raw file Click Here

Output

First Distance : F: 11 I:10

Second Distance :F: 5 I:11

First Distance :F: 5 I:11

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