Why doesn't the attributor copy the object?



  • Why in the first line z = *thisz.val copying the meaning this->valBut second. z.val becomes equal. 0♪ As a result b.val = 6

    #include <iostream>
    

    using namespace std;

    class integer2
    {
    private:
    int val;
    public:
    integer2(int v0)
    {
    val = v0;
    }
    integer2& operator+(int s)
    {
    integer2 z(0);
    z = *this;
    z.val = z.val + s;
    return z;
    }

    int getVal()
    {
        return val;
    }
    

    };

    int main()
    {
    integer2 a(5), b(0);
    b = a + 5 + 6;
    return 0;
    }



  • Local variables created on the glass shall be destroyed when the visibility is out (in this case the output is from the method).

    So, returning integer2& You're pointing to the object. integer2 z( 0 );which no longer exists is UB.

    In accordance with standards C and C++, if the programme leads to overcrowding of a whole variable, or to any of hundreds of other &quot; undetermined actions &quot; (undefined behaviour, UB), the result of the programme may be any: it can implant on the Twitter of indecency, may disk you...
    (c) Habra post

    Right operator+ in your case:

    integer2 operator+( const int num )
    {
        integer2 temp( *this );
        temp.val += num;
        return temp;
    }
    



Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2