I have a header file which contains a class with an assignment operator. Now I want to define my function inside my .cpp file.
My header file contains: Car &operator=(const Car &other);
Now in my cpp file I would like to do something like: Car::Car &operator=(const Car &other)
{
}
Unfortunately this doesn't seem to be the right syntax. So how can I define my assignment operator when I have the function declaration and the function definition separated?
An assignment operator is the operator used to assign a new value to a variable, property, event or indexer element in C# programming language. Assignment operators can also be used for logical operations such as bitwise logical operations or operations on integral operands and Boolean operands.
“=”: This is the simplest assignment operator. This operator is used to assign the value on the right to the variable on the left. For example: a = 10; b = 20; ch = 'y';
In C++, assignment operators are used to assign values to variables.
Overloading the assignment operator (operator=) is fairly straightforward, with one specific caveat that we'll get to. The assignment operator must be overloaded as a member function. This will call f1. operator=(f1), and under the simplistic implementation above, all of the members will be assigned to themselves.
You're almost there; you need to qualify the function name to indicate that it's a member:
Car &Car::operator=(const Car &other) { }
^^^^^
I write my operators as follows
in.h
Car& operator=(const Car &other);
in cpp
Car& Car::operator=(const Car &other) { }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With