Lab #8, Friday October 19

The purpose of this lab is to give you practice with overloading operators and separate compilation.

The following is the header and implemenation for a Pair class. The class simply stores a pair of numbers. There is an overloaded member operator + that adds two pairs together or adds a constant value to each number in the pair. Here is the class definition that goes in the file Pair.h:

#pragma once
class Pair
{
private:
  int num1, num2;
public:
  Pair();
  Pair(int num1, int num2);
  int get1();
  int get2();
  Pair operator+(const Pair &other);
  Pair operator+(int otherNum);
};
Here is the implementation that goes in the file Pair.cpp:
#include "Pair.h"

Pair::Pair() : num1(0), num2(0)
{
}

Pair::Pair(int num1, int num2) : num1(num1), num2(num2)
{
}

int Pair::get1()
{
 return num1;
}

int Pair::get2()
{
 return num2;
}

// Return a new pair that adds the corresponding numbers
Pair Pair::operator+(const Pair &other)
{
  Pair newPair(this->num1, this->num2);
  newPair.num1 += other.num1;
  newPair.num2 += other.num2;
  return newPair;
}

// Return a new pair that adds otherNum to num1 and num2
Pair Pair::operator+(int otherNum)
{
  Pair newPair(this->num1, this->num2);
  newPair.num1 += otherNum;
  newPair.num2 += otherNum;
  return newPair;
}
Here is the contents of the file main.cpp:
#include <iostream>
#include "Pair.h"

using namespace std;

int main()
{
  Pair p1(5,10);
  Pair p2(1,2);

  // Outputs 5 and 10
  cout << p1.get1() << " " << p1.get2() << endl;
  // Outputs 1 and 2
  cout << p2.get1() << " " << p2.get2() << endl;

  Pair p3 = p2 + p1;
  // Outputs 6 and 12
  cout << p3.get1() << " " << p3.get2() << endl;

  p3 = p3 + 2;
  // Outputs 8 and 14
  cout << p3.get1() << " " << p3.get2() << endl;
}
As written, the program runs as intended! But if we change the last overloaded + so that the 2 is the first operand then the program will not compile. In other words, we have problems if we write:
   p3 = 2 + p3;
 
To do:
  1. Put the original code into separate files, compile, and run it. You can use the programming environment of your choice. If you're using Linux and compiling from the command line, don't forget you need to compile main.cpp and Pair.cpp together unless you create a Makefile or do separate compilation.
  2. Change the line p3 = p3 + 2; to p3 = 2 + p3; and explain why it doesn't work.
  3. Overload the + operator as a global friend function/operator so that all of these work: 2 + p3 or p3 + 2 or p1 + p2 or p2 + p1 (the last two already work in the original code, but you should rewrite them as friends also to be consistent and for a little extra practice). The best place to put the global friend function(s) is in main.cpp (don't put it in Pair.cpp).
  4. Does the overloaded + operator even need to be a friend in this program? Tell the TA or instructor why or why not.
Show your code/program and explanations to the lab assistant for credit, or email to kjmock@alaska.edu for lab credit.