Bad value result from operator= using objects

Hello all,

I keep getting an undesired value in this code. I've tried several methods, but none are giving me the correct answer. The out put is always zero, when in this case it should be 10!!

Here's the object structure:
1
2
3
4
5
6
7
8
9
10
11
12
13
template<class T, class _b>
struct quantity
{
   private: T value;
   public:
      explicit quantity(T val): value(val) {};
      T getValue() { return value; };

      template<class V> quantity<T,_b> operator=(quantity<V,_b> qty)
      {
         return quantity<T,_b>(qty.getValue());
      }
};


Here's the operation:
1
2
3
4
5
6
7
8
9
10
11
12
int main()
{
   quantity<int, bool> m(20);
   quantity<float, bool> m_f(10);
   quantity<double, bool> m_d(NULL);

   m_d = m_f;
   
   std::cout << m_d.getValue() << std::endl;

   return 0;
}


Why does it seem that the assignment operator is the harder operator to overload? Maybe it's just my luck, but I seem to always run into issues whenever I work with it. I hardly ever experience errors when overloading any of the other operators.

Thank you.
The assignment operation has signature:
 
T& operator=(const T&)


You should follow the convention.
The way you have implemented operator= doesn't modify the object on the LHS. Normally operator= modifies the object on the LHS and returns a reference to that object.
But when I try:

1
2
3
4
template<class V>& quantity<T,_b> operator=(const quantity<V,_b>& qty)
{
         return quantity<T,_b>(qty.getValue());
}


I get this error: cannot convert 'this' pointer from 'const quantity<T,_b>' to 'quantity<T,_b> &'

I get the feeling that I need to reference the object using this, as Peter87 said, but as you can see I'm not good at all with operator functions, and I truthfully can't seem to figure out how to do it using the 'this' pointer.
1
2
value = qty.getValue();
return *this;
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
template<class T, class _b>
struct quantity
{
private:
    T   value;

public:
    explicit quantity(T val) :
        value(val)
    {
    }

    T getValue() const
    {
        return value;
    }

    template<class V>
    quantity<T,_b>& operator=(const quantity<V,_b>& qty)
    {
        value = qty.getValue();
        return *this;
    }
};

int main()
{
    quantity<int, bool> m(20);
    quantity<float, bool> m_f(10);
    quantity<double, bool> m_d(0);

    m_d = m_f;

    return 0;
}
Yeah... I see it now. :( Blinded by the light.

Can't believe I missed my on class variable. lol

Thanks.
Topic archived. No new replies allowed.