Search code examples
c++operator-overloadingimmutabilityoperator-keywordassignment-operator

How Can I Avoid Writing an Assignment Operator for my Immutable Class


I have written an immutable class Coords, with only two members - const int x and const int y. However, the compiler wants me to write an assignment operator, which, from what I can gather, makes no sense for an immutable type. Here's an example:

//location is a Coords* and Coords::DOWN is a static const Coords&.   
Coords& next = Coords(location);
next = next + Coords::DOWN;

Intellisense does not like the use of "=" in line 3. I figure that the issue is that I've already allocated memory for 'next', so when I want to replace the stuff in that memory with something else, it does not like that. Am I correct? How can I get around this issue?

Thanks!


Solution

  • You don't want 'next' to be reference-to-Coords. You want it to be an object of type Coords. Try this:

    Coords next = *location + Coords::DOWN
    

    The destructor for 'next' will be called by the run time when 'next' goes out of scope (often at the end of the method)

    You will want to write a + (plus operator) override in any event. (Your object is not immutable. You need to read up on that).