1

I'm just a beginner in the C++ language and I have some questions on this piece of code. I am trying to overload some operators.

string& operator = (char R) { string T = R ; *this = T; return *this; }

First Question: Why I need to overload the equal operator while the constructor can do the job?
Second Question: (Not Related) What does (char R) means?

5

4 Answers 4

2

First Question: Why I need to overload the equal operator while the constructor can do the job?

The constructor is designed to "construct" an object ... while there is something called a copy-constructor, it is not designed to actually copy an already existing object into another already existing object of the same (or convertable) type ... that is the job of the operator=. Also you are not "overloading" the operator= method, but rather creating a user-defined version of the method to be used instead of the default compiler-created method for the object type which would simply brute-force copy the bits of the memory footprint of one object into another ... if your object is managing it's own pointers, etc., such a brute-force copy can be a very bad thing as pointer ownership becomes ambiguous, etc.

2
  • Got the point.. I forgot that the constructor is only called once.. so because of that we use those user-defined versions for farther edit.. right? Mar 9, 2013 at 13:15
  • Right, after the constructor is called and the object instance exists, then the assignment operator is used for copies. Keep in mind the "Rule of Three" though ... if you actually need a user-defined assignment operator, then you probably also need a user-defined copy-constructor and destructor for your class since you are most likely managing resources the default compiler versions of those methods will fail to handle correctly.
    – Jason
    Mar 10, 2013 at 8:26
0

(char R) is the right-side argument of the operator (here =)

You want to do that so you can set a value after initialization

//constructor
Foo a('f')
//copy constructor
Foo b = Foo('p');
// operator=
b = 'g';
0

(char R) is the argument to the operator just like you have an argument to a normal function.

0

Operator overloading in C++ . One of best version here.

http://msumca2012.blogspot.in/2013/03/oop-41-operator-overloading-in-c.html

1
  • Welcome to Stack Overflow! Whilst this may theoretically answer the question, it would be preferable to include the essential parts of the answer here, and provide the link for reference.
    – Emil
    Mar 10, 2013 at 16:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.