I don't understand the function Bar operator +()
"
Rightfully so. It does not make much sense (of course, with example names like "Foo" and "Bar", few things do). It declares a unary plus operator.
Which is already quite an exotic feature of the language. Here is an example:
#include <iostream>
int main()
{
int i = 5;
std::cout << +i << "\n";
}
This program will, unsurprisingly, print 5
. There are some uses cases for it, though. See What is the purpose of unary plus operator on char array? and What does the unary plus operator do?.
In your code, you would call the operator like this:
Foo f;
+f;
The other strange thing about the code you show is that the operator returns Bar
rather than Foo
as one would expect (although, again, with names like "Foo" and "Bar", one cannot really be sure about the supposed intent of the code).
The operator is also private
, which means that it can only be used from inside Foo
's own functions or friends. This can hardly be right.
int value= b1->num +b2->num;
This is undefined behaviour because you try to access members via uninitialised pointers[*]. Or you are not showing us the code where b1
and b2
are initialised and/or assigned.
Bar * b = new Bar(value);
return (*b);
This creates a memory leak, because the Bar
object which lives in the memory dynamically allocated by new
is copied and will never be destroyed, as the one and only pointer to it (b
) is lost.
Perhaps your friend wants to create possibility of adding Bar
and Foo
together. If that is the case, then a lot of things have gone wrong. The function has the wrong interface and the wrong implementation.
Please go to http://en.cppreference.com/w/cpp/language/operators and read the section about binary arithmetic operators to see how this is done correctly.
Or just forget about operator overloading for now. Some more basic knowledge about the language (e.g. nullptr
/ pointer initialisation / pointers in general) seems to be missing.
[*] not nullptr
s as a previous version of this answer said