Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to define an assignment operator outside my header file in C++?

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?

like image 528
Chris Avatar asked Jul 05 '12 15:07

Chris


People also ask

How do you define assignment operator?

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.

How do you write an assignment operator?

“=”: 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';

Is ++ an assignment operator?

In C++, assignment operators are used to assign values to variables.

How do you write an assignment overloaded operator?

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.


2 Answers

You're almost there; you need to qualify the function name to indicate that it's a member:

Car &Car::operator=(const Car &other) { }
     ^^^^^
like image 200
Mike Seymour Avatar answered Sep 30 '22 01:09

Mike Seymour


I write my operators as follows

in.h
Car& operator=(const Car &other);
in cpp
Car& Car::operator=(const Car &other) { }
like image 43
Moataz Elmasry Avatar answered Sep 30 '22 00:09

Moataz Elmasry