0

I overloaded operator = for the class TextureImage in the class but the compiler keep saying no viable operator "=" .

    TextureImage& operator=(TextureImage i){
      this->x = i.getX();
      this->y = i.getY();
      this->n = i.getN();
      this->data = i.getData();
      return *this;
    }

If I add const to the function the compiler says I can't assign to non-static data member within const member function.

So how to overloaded operator = here

Mike Kinghan
  • 55,740
  • 12
  • 153
  • 182
JOYD
  • 45
  • 1
  • 1
  • 4
  • It should accept a const reference to the object being copied `=(TextureImage const & i)`. – user7860670 May 20 '17 at 16:00
  • @VTT That wouldn't matter much, but yes that's the canonical form. – πάντα ῥεῖ May 20 '17 at 16:03
  • Copy&paste the complete message! –  May 20 '17 at 16:05
  • 1
    If any of `x`, `y`, `n`, or `data` are pointers or contain a resource that is not trivially duplicated you will have a logic error to deal with once the program compiles. If not, it is possible that you don't need an assignment operator at all (see [The Rule of Zero](http://en.cppreference.com/w/cpp/language/rule_of_three)). [The Copy and Swap Idiom](http://stackoverflow.com/questions/3279543/what-is-the-copy-and-swap-idiom) may assist you in writing future assignment operators. – user4581301 May 20 '17 at 16:18

1 Answers1

2

You certainly don't want to have the assignment operator overloaded as const member function. If you insist, make all the member variables mutable.

The canonical form looks like

TextureImage& operator=(const TextureImage& i) {
   x = i.x;
   y = i.y;
   n = i.n;
   data = i.data;
   return *this;
}

Note you don't need to use the getters there.

If there's nothing more to do there, you don't need to implement your own assignment operator, since the compiler already generates that code automatically or on demand

TextureImage& operator=(const TextureImage& i) = default;

Though I suspect data needs some more special handling, since it sounds that is kind of array or pointer member variable.

In this case I would recommend you use a std::array or std::vector as data member and stick with the default implementation.

πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190