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?

geekybedouin
  • 549
  • 1
  • 11
  • 23

4 Answers4

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.

Jason
  • 31,834
  • 7
  • 59
  • 78
  • 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? – geekybedouin Mar 09 '13 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"](http://en.wikipedia.org/wiki/Rule_of_three_(C%2B%2B_programming)) 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 '13 at 08: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';
drahnr
  • 6,782
  • 5
  • 48
  • 75
0

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

uba
  • 2,012
  • 18
  • 21
0

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

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

  • Welcome to Stack Overflow! Whilst this may theoretically answer the question, [it would be preferable](http://meta.stackexchange.com/q/8259) to include the essential parts of the answer here, and provide the link for reference. – Emil Mar 10 '13 at 16:03