Overloaded =, ==, !=
2002-09-14 21:40:16
Category: cpp:overloading
Description: How to overload the copy constructor and the compare operators within your class.
Author: detour
Viewed: 2076
Rating: (5 votes)


/* equal_overl.cpp by detour@metalshell.com
 * 
 * If you need to compare or set classes equal
 * to one another, the best way is to overload
 * the equality functions.  This is a basic example
 * on how to do just that.
 *
 * http://www.metalshell.com/
 *
 */
 
#include <string>
#include <iostream>
 
using namespace std;
 
class Beer{
   private:
      string name;
      int supply;
 
   public:
      Beer(string b_name, int b_supply) {
         name = b_name;
         supply = b_supply;
      }
      void printBeer() {
         cout << "Type: " << name << endl;
         cout << "Amount: " << supply << endl;
         cout << "-------------------------\n";
      }
      const Beer & operator=(const Beer &rBeer) {
         name = rBeer.name;
         supply = rBeer.supply;
 
         return *this;
      }
      bool operator==(const Beer &rBeer) const {
         return (name == rBeer.name && supply == rBeer.supply);
      }
      bool operator!=(const Beer &rBeer) const {
         return (name != rBeer.name || supply != rBeer.supply);
      }
};
 
int main() {
   Beer myBeer("Bud Light", 6);
   Beer frndBeer("Budweiser", 5);
   
   myBeer.printBeer();
   frndBeer.printBeer();
 
   // Uses the overloaded == function
   if(myBeer == frndBeer)
      cout << "\nBeer is the same." << endl;
   else
      cout << "\nBeer is different." << endl;
 
   // Uses the overloaded copy constructor.
   myBeer = frndBeer;
 
   // Uses the overloaded != function
   if(myBeer != frndBeer)
      cout << "Copy constructor has failed." << endl;
   else
      cout << "Copy constructor worked, you both have equal beer\n\n";
 
 
   myBeer.printBeer();
   frndBeer.printBeer();
   
   return 0;
}