M
M
Max Suprunenko2015-10-04 20:41:45
C++ / C#
Max Suprunenko, 2015-10-04 20:41:45

What's the difference between String& operator+ (); and String operator+();?

What's the difference between String& operator+ (); and String operator+(); ?
Stroustrup constantly writes String& operator+ () and does not explain why.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Mercury13, 2015-10-04
@msuprunenko

The first returns by reference, the second by value. The first simply returns the address, the second makes a copy. How to determine what we need?
Here we have the "unary plus" operation, which, most likely, does nothing and return *this. This very *this is definitely not local. Therefore, we return by reference, String&.
Now let's take binary addition. We create a new string (as a local variable, of course), enter the amount into it ... and so that it does not disappear before the calling subroutine picks it up, we return by value (String).
For virtual functions, they usually play it safe and return by value (String). They don’t care about copying, but if suddenly a descendant needs to return something local, it will return it without any problems.

class Father {
private:
  String fName;
public:
  virtual String& name() const { return fName; }  // пока всё нормально, но…
};

class Son : public Father {
public:
  String& name() const
     { return Father::name() + "'s son"; }   // ошибка, возвращаем локальную переменную!
};

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question