Saturday, December 16, 2017

C++ Overloaded Operator

As it is a feature of C++, overloading the language native operators is worth spending a few minutes to examine. In this example, the plus operator will be used to get the sum of the areas of two Rectangle objects when they are added together.
#include <iostream>

using namespace std;

class Rectangle {
    double width, height;
  public:
    // declare constructor
    Rectangle(double, double);

    // define the getArea method
    double getArea() { 
      return width * height;
    }

    // define the method run by the overloaded plus operator
    double operator+(const Rectangle& other) {
      return (width * height) + (other.width * other.height); // return area + area
    }
};

// define the constructor
Rectangle::Rectangle(double w, double h) {
  width = w;
  height = h;
}

int main() {
  Rectangle box(1.20, 1.33);
  cout << box.getArea() << endl;

  Rectangle quad(2.0, 3.0);

  cout << box + quad << endl;  // use the overloaded plus operator
}
Commands to compile and link the code and run the program followed by the program's output
$ g++ -std=c++14 -c -o rectangle.o rectangle.cpp
$ g++ -o rectangle rectangle.o
$ ./rectangle
1.596
7.596
$ 

Another Example of Overloaded Operator

#include <iostream>
using namespace std;

struct MatchCheck {
  virtual bool operator()(string&)=0; // pure virtual 
};

struct StringCheck:public MatchCheck {
  virtual bool operator()(string &comp) {
    return comp == "bacon";
  }
};

int main() {
  string eggs = "eggs";
  string bacon = "bacon";
  StringCheck isBacon;
  cout << "is it eggs? " << (isBacon(eggs) ? "yes" : "no") << endl;
  cout << "is it bacon? " << (isBacon(bacon) ? "yes" : "no") << endl;
}