Search code examples
c++operator-overloadingassignment-operator

Can assignment operator be overloaded to return the value of a property of a class?


I wanted to return the value of a property of a class using assignment operator. I tried to fulfill this purpose. I searched a lot on the web but all of the websites I visited talked about how to overload assignment operator to do like a copy constructor of a class like this: class_t& operator=(class_t&);. Can anybody help me overload this operator to return the value of a property of a class?

This is my code:

class A_t
{
private:
  int value = 0;

public:
  int operator = (A_t);  // I failed to overload assignment operator for this
  A_t& operator = (int); // I succeeded to overload assignment operator for this
  int Value();
  void setValue(int);
};

A_t& A_t::operator = (int value)
{
  this->setValue(value);
  return *this;
}

int operator = (A_t &data)
{
  return data.value;
}

int A_t::Value() { return this->value; }
void A_t::setValue(int data) { this->value = data; }

int main()
{
    A_t object = 3;
    int value = object; // Error: cannot convert 'A_t' to 'int' in initialization

    cout << value << endl;
    return 0;
}

Solution

  • You can’t overload operator = for this. What you can do instead is overload the implicit conversion-to-int operator inside the class:

    operator int() const { return value; }
    

    However, think carefully whether this is actually a good idea in your case. Implicit conversions should usually be avoided at all cost, because it’s very error-prone (many smart people think C++ shouldn’t allow defining custom implicit conversions at all!).