Search code examples
c++operator-overloadingassignment-operator

What are the consequences of "screwing up" the assignment operator?


I want to have double values with a name and units, but I want to use them as if they were simple doubles. For example I want to use them like this:

int main(){
    NamedValue a("a","m");
    NamedValue b("b","m");
    NamedValue c("c","m^2");
    a = 3;
    b = 5;
    c = a*b;
    std::cout << a << b << c <<  std::endl;
    return 0;
}

and the output should be:

a = 3 m
b = 5 m
c = 15 m^2

I came up with this solution:

class NamedValue  {
public:
    NamedValue(std::string n,std::string u) : name(n),units(u){}
    const std::string name;
    const std::string units;
    void operator=(double v){this->value = v;}
    void operator=(const NamedValue& v){this->value = v.value;}
    operator double() const { return value; }      
private:
    double     value;
};

std::ostream& operator<<(std::ostream& stream,const NamedValue& v) {
     stream << v.name << " = " << (double)v <<  " " << v.units << std::endl;
     return stream;
}

Unitl now it works nicely, but I am mainly concerned about the assignment operator void operator=(const NamedValue& v){this->value = v.value;} that is not exactly doing, what one normally would expect of an assignment operator.

Are there any bad consequences that I will face?

I am thinking about things like passing an object as parameter and stuff like that. However, a function like this

NamedValue test(NamedValue x){return x;}

works without problems, as there is no assignment involved (only copy constructor). Am I missing something? Is there anything else I should be aware of?

ps: Just in case you wonder, at the moment I do not care about checking the units when doing calculations.


Solution

  • The assignment operator is totally fine. The only thing unusual about it is that you did not return the object so the operator calls cannot be chained. Otherwise, it's a completely normal operator.