Hello Everyone,

I am trying to implement an overloaded < operator. I found the code below at

http://www.java2s.com/Tutorial/Cpp/0200__Operator-Overloading/Theoverloadedlessthanoperatorswithdoublevalue.htm

I am trying to use this as a tutorial, but I don't understand what is happening on line 23-24. I am also a little fuzzy on line 9.

Why can't it be written like this?

Box(double aLength, double aWidth, double aHeight) {}

Here is the "tutorial"

#include <iostream>
#include <cstdlib>             
#include <ctime>                
using std::cout;
using std::endl;

class Box {
  public:
    Box(double aLength, double aWidth, double aHeight):length(aLength), width(aWidth), height(aHeight) {}

    double volume() const {
      return length*width*height;
    }

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

    inline bool operator<(const Box& aBox) const {          //returns volume to be used in main()    
      return volume() < aBox.volume();
    }

    inline bool operator<(const double aValue) const {      //what is this doing?
      return volume() < aValue;                             //what is this doing?
    }


  private:
    double length;
    double width;
    double height;
};


int main() {


  Box firstBox(17.0, 11.0, 5.0);

  if(firstBox < 100000){
    cout << "less than";
  }else{
    cout << "not less than";
  }

  return 0;
}

Recommended Answers

All 4 Replies

Line 9 cant be blank because you have to do something with the parameters you pass it. Lines 23-24 are there to compare a double value against the volume of the box.

Thank you. I follow you on line 9. I re-wrote the line as shown below and it compiled.

Box(double aLength, double aWidth, double aHeight)
{
    length = aLength;
    width = aWidth; 
    height = aHeight;
}

Is my comment on line 19 correct? It must not be completely correct. If it were, I don't see the need for lines 23-24.

No you are not correct. The function on line 19 is used to compare to box objects.

commented: I like this guy +3
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.