C++/Operator Overloading
Expert: vijayan - 2/18/2010
QuestionQUESTION: Hi Vijayan,
I have doubt on Operator Overloading fucntions
Integer& operator+=(const Integer& other)
friend std::ostream& operator<<(std::ostream& out, const Integer& i)
1.In the above Operator Overloading functions why i have to pass only references as arguments and references as return values ?
Integer* operator+=(const Integer* other) , Integer operator+=(const Integer other)
friend std::ostream* operator<<(std::ostream* out, const Integer* i),friend std::ostream operator<<(std::ostream out, const Integer i)
1.will these functions work for passing and returning pointer and normal values? if it won't work what is the reason?
Many Thanks in Advance
ANSWER: > will these functions work for passing and returning pointer
No. A pointer in a standard built-in type. Operators for all standard built-in types are pre-defined and can not be changed. Operators can be overloaded only for user defined types (struct/class or enum).
> will these functions work for passing and returning normal values?
Integer& operator+=(const Integer& other) ;
The += is a variant of the assignment operator, it modifies the object on which it is applied (the one on the left of the +=). So operator+= has to be a non-const member function. However the Integer on the right of the assignment (other) may be passed by value. operator += can return by value (return a copy); but this is considered bad form for two reasons - efficiency and deviation from usual meaning of +=.
friend std::ostream& operator<<(std::ostream& out, const Integer& i)
std::ostream is not a copyable object (no public copy constructor), it can only be passed and returned by reference. As before, the Integer on the right of the assignment (other) may be passed by value.
---------- FOLLOW-UP ----------
QUESTION: Hi Vijayan,
I am sorry not able to understand your point
ANSWER: > will these functions work for passing and returning pointer
No. A pointer in a standard built-in type. Operators for all standard built-in types are pre-defined and can not be changed. Operators can be overloaded only for user defined types (struct/class or enum).
why i cant do like Integer* operator+=(const Integer* other);
pointer and references also C++ built in Operators only right?
Answer> why i cant do like Integer* operator+=(const Integer* other);
Because it violates the International Standard for C++.
"An operator function shall either be a non-static member function or be a non-member function and have at least one parameter whose type is a class, a reference to a class, an enumeration, or a reference to an enumeration. ..." - ISO/IEC 14882 section 13.5.6
In simple words, at least one type involved in an overloaded operator must be a user defined type. And pointers are not user defined types; they come with the language.