Operator Overloading Programming Exercise 3

Operator overloading defines an additional meaning of operator.

Operator overloading is a feature of C++ programming language that allows a programmer to redefine the meaning of operator when they operate on class object.

If you don’t familiar with operator overloading please read the following article first.

What is Class?

Class may be defined as the collection of objects which have some properties and functions.

If you want to know more about classes, please read the following article.

Question Number 3

Write a class Array that contains an array of integers as data member.
 The class contains the following member functions:
1. A constructor that initializes the array elements to -1.
2. Input function to input the values in the array.
3. Show function to display the values in the array.
4. Overload ==operator to compare the values of two objects. The overloaded
function returns 1 if all values of both objects are same and returns 0 otherwise.

#include<iostream>
using namespace std;

class Array
{
	private:
		int arr[5];
		public:
			Array();
			void input();
			void show();
			int operator == (Array a);
};
  Array::Array()
  {
  	int i;
  	for(i = 0; i < 5; i++)
  	arr[i] = -1;
  }
  void Array::input()
  {
  	int i;
  	for(i = 0; i < 5; i++)
  	{
  		cout<<"Enter an integer: ";
  		cin>>arr[i];
  	}
  }
  void Array::show()
  {
  	int i;
  	cout<<"Array values: ";
  	for(i = 0; i < 5; i++)
  	  cout<<arr[i]<<" ";
  }
  int Array::operator == (Array a)
  {
  	int i, eq = 1;
  	for(i = 0; i < 5; i++)
  	  if(arr[i] != a.arr[i])
  	    eq = 0;
  	return eq;
  }
   main()
   {
   	Array x, y;
   	int n;
   	x.input();
   	y.input();
   	if(x == y)
   	cout<<"Both arrays are equal.";
   	else
   	cout<<"Both arrays are different.";
   }

Leave a Reply