Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why two Static object inside an operator overload implementation will always be equal in c++?

Tags:

c++

object

static

I was readin effective c++. They have given an example as below :

class Rational{
    public : Rational (int num=0, int deno=1);
    private : int n,d;
              friend Rational operator*(const Rational &lhs, const Rational &rhs);

 }


 Rational& operator*(const Rational& lhs, const Rational& rhs)
 {
     static Rational result;
     result = f(lhs.n*rhs.n, lhs.d*rhs.d) //some function f which multiply num 
                                          //and denom which returns Rational type

      return result;
 }

  bool operator==(const Rational& lhs, const Rational& rhs);

  int main()
  {
        Rational a,b,c,d;
        .....
        if((a*b)==(c*d)){
        ....
        }
        else {
        .....
        }
  }

Why the compariosion (a*b)==(c*d) always evaluate to true?

The == operator will be evaluated as if(operator==(operator*(a,b),operator*(c,d))) Effective C++ says - the operator == will be asked to compare the value of static Rational object inside operator * with the value of the static Rational object inside * operator. Why these static values will always be equal?

like image 895
sarda Avatar asked Dec 28 '25 07:12

sarda


1 Answers

Both expressions in this comparison ((a*b)==(c*d)) return a reference to the same object - static Rational result from inside operator*. It has static storage duration and it lives from the moment the execution flow reaches it for the first time and until the program exits (in other words, it persists between the calls to operator*).

Unless the operator== does something weird, an object is supposed to be equal to itself and the result will always be true.

like image 69
jrok Avatar answered Dec 30 '25 22:12

jrok



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!