Implementing an Overloaded Operator - C++ Class

C++ examples for Class:Operator Overload

Introduction

Here's the function member to overload the < operator in the Pool class definition:

class Pool
{
private:
  // Members as before...

public:
 bool operator<(const Pool& aPool) const;          // Overloaded 'less-than' operator

// The rest of the Pool class as before...
};

Because you're implementing a comparison, the return type is bool.

The operator<() function will be called as a result of comparing two Pool objects using <.

Because the function doesn't change either operand, the parameter and the function are specified as const.

if(pool1 < pool2)
  std::cout << "pool1 is less than pool2" << std::endl;

you could write it like this in the if statement:

if(pool1.operator<(pool2))
   cout << "pool1 is less than pool2" << endl;

Demo Code

#include <iostream>

class Pool/*w  w w. j  a  v a  2  s. co  m*/
{
private:
  double length {1.0};
  double width {1.0};
  double height {1.0};

public:
  // Constructors
  Pool(double lv, double wv, double hv) : length{lv}, width{wv}, height{hv} {}

  Pool() {}                                               // No-arg constructor

  Pool(const Pool& pool) :                                  // Copy constructor
      length {pool.length}, width {pool.width}, height {pool.height} {}

  double volume() const                                  // Function to calculate the volume
  { return length*width*height; }

  // Accessors
  double getLength() const { return length; }
  double getWidth() const { return width; }
  double getHeight() const { return height; }

  bool operator<(const Pool& aPool) const                  // Less-than operator
  { return volume() < aPool.volume(); }
};

// Implementing a less-than operator
#include <iostream>
#include <vector>

int main()
{
  std::vector<Pool> pools {Pool {2.0, 2.0, 3.0}, Pool {1.0, 3.0, 2.0},
                          Pool {1.0, 2.0, 1.0}, Pool {2.0, 3.0, 3.0}};
  Pool smallPool {pools[0]};
  for (auto& pool : pools)
  {
    if (pool < smallPool) smallPool = pool;
  }

  std::cout << "The smallest pool has dimensions :"
    << smallPool.getLength() << "x" << smallPool.getWidth() << "x"
    << smallPool.getHeight() << std::endl;
}

Result


Related Tutorials