| | |
Operator Overload Question
Please support our C++ advertiser: Intel Parallel Studio Home
![]() |
•
•
Join Date: May 2008
Posts: 2
Reputation:
Solved Threads: 0
Hello all,
I have a doubt concerning to overloaded operators.
Does the compiler create new temporary object to the elements involved on the overloaded operation?
E.g. Operator + overloaded.
a = b + c;
Does the compiler creat temporary object for b and c?
See the following code and the print outs. When the + operator is called, 3 new objects are destroyed and I cant see the construction message.
I guess the default copy constructor is called by the compiler, but I am not sure.
Does any one knows the answer for this question???
Thank you,
Helbert
I have a doubt concerning to overloaded operators.
Does the compiler create new temporary object to the elements involved on the overloaded operation?
E.g. Operator + overloaded.
a = b + c;
Does the compiler creat temporary object for b and c?
See the following code and the print outs. When the + operator is called, 3 new objects are destroyed and I cant see the construction message.
I guess the default copy constructor is called by the compiler, but I am not sure.
Does any one knows the answer for this question???
Thank you,
Helbert
C++ Syntax (Toggle Plain Text)
// Class1.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include <iostream> using namespace std; class Rectangle{ int x, y; public: Rectangle(int x, int y); Rectangle(){cout << "Created: " << this << endl;}; void set_values(int x, int y); int getX() {return x;}; int getY() {return y;}; int area() {return (x*y); } Rectangle operator +(Rectangle); ~Rectangle(); }; Rectangle::Rectangle(int x, int y){ this->x = x; this->y = y; cout << "Created: " << this << endl; } Rectangle::~Rectangle(){ cout << "Retangle has been destroyed " << this << endl; } Rectangle Rectangle::operator +(Rectangle add){ Rectangle tmp; tmp.set_values(add.getX(), add.getY()); return tmp; } void Rectangle::set_values(int x, int y){ this->x = x; this->y = y; } int main(){ Rectangle rect(2,3); Rectangle rectb(1,2); Rectangle rectc; cout << "AREA: " << rect.area() << endl; cout << "AREA: " << rectb.area() << endl; rectc = rect + rectb; cout << "AREA: " << rectc.area() << endl; return 0; }
•
•
Join Date: Dec 2006
Posts: 1,089
Reputation:
Solved Threads: 164
with
// a, b, c are Rectangles
the return value is an anonymous temporary, which is constructed on return (and destroyed).
if you got a third construct/destroy, the (perhaps old?) compiler you are using is not doing any NRV optimization (in the implementation, temporary
to avoid the copy, and to make the code const-correct, write
note: adding rectangles does not seem to be intuitive.
C++ Syntax (Toggle Plain Text)
class Rectangle { //... public: //... Rectangle operator +(Rectangle); //... };
// a, b, c are Rectangles
a = b + c ; evaluates to a = b.operator+(c) ; since c is passed by value, a copy of c is made (and destroyed later).the return value is an anonymous temporary, which is constructed on return (and destroyed).
if you got a third construct/destroy, the (perhaps old?) compiler you are using is not doing any NRV optimization (in the implementation, temporary
Rectangle tmp is constructed and destroyed on return).to avoid the copy, and to make the code const-correct, write
class Rectangle
{
//...
public:
//...
Rectangle operator+ ( const Rectangle& ) const ;
//...
};note: adding rectangles does not seem to be intuitive.
Last edited by vijayan121; May 10th, 2008 at 11:54 pm.
•
•
Join Date: May 2008
Posts: 2
Reputation:
Solved Threads: 0
Thanks for the explanation.
About the solution ( const Rectangle& ) const ; , if I do so, I get a compiling error ": error C2662: 'Rectangle::getX' : cannot convert 'this' pointer from 'const Rectangle' to 'Rectangle &' Conversion loses qualifiers
. Any clue??
About the "adding rectangles" stuff, it is just an exercice. I started with the rectangles and then adding functionalities :-)
Thanks again!
About the solution ( const Rectangle& ) const ; , if I do so, I get a compiling error ": error C2662: 'Rectangle::getX' : cannot convert 'this' pointer from 'const Rectangle' to 'Rectangle &' Conversion loses qualifiers
. Any clue??
About the "adding rectangles" stuff, it is just an exercice. I started with the rectangles and then adding functionalities :-)
Thanks again!
You can't overload the + operator to be const unless you change the operation to not modify *this. In other words, if you change *this, get rid of the second const.
The + operator typically is expected to not modify the b object (as vijayan121 explained with
Hence, the typical layout of such a function is:
Unless your object uses a lot of memory or other resources or has existential side-effects, I wouldn't really worry too much about temporaries. For something like your Rectangle, the difference is negligible: copying is fast and often optimized away.
Hope this helps.
[edit]
Oh yeah, often, to avoid duplicating code, the + operator is often written in terms of the += operator:
The + operator typically is expected to not modify the b object (as vijayan121 explained with
a = b.operator+(c) ;).Hence, the typical layout of such a function is:
C++ Syntax (Toggle Plain Text)
Rectangle Rectangle::operator + (const Rectangle& rect) const { Rectangle result; result.x = this->x + rect.x; ... return result; }
Unless your object uses a lot of memory or other resources or has existential side-effects, I wouldn't really worry too much about temporaries. For something like your Rectangle, the difference is negligible: copying is fast and often optimized away.
Hope this helps.
[edit]
Oh yeah, often, to avoid duplicating code, the + operator is often written in terms of the += operator:
C++ Syntax (Toggle Plain Text)
Rectangle Rectangle::operator + (const Rectangle& rect) const { return (Rectangle( *this ) += rect); }
Last edited by Duoas; May 11th, 2008 at 10:47 pm.
![]() |
Similar Threads
- help (overload << in a template class ) (C++)
- operator overload (C++)
- How to overload + operator for STL Vectors (C)
- Write to Screen and File{I-O question} (C++)
- How do I overload [] operator for pointers (C++)
- Operator Overloading Question (C++)
- Overloading assignment operator (C++)
- Simple Class Question (C++)
- noob question (C)
- another merge sort question (C++)
Other Threads in the C++ Forum
- Previous Thread: What are the results for this?
- Next Thread: looking to make a game script with c/c++ language
Views: 530 | Replies: 3
| Thread Tools | Search this Thread |
Tag cloud for C++
6 api array arrays based beginner binary bmp c++ c/c++ calculator char class classes code compile compiler console conversion convert count data delete deploy dll download dynamic dynamiccharacterarray encryption error file format forms fstream function functions game givemetehcodez graph gui homeworkhelp iamthwee ifstream input int java lib library lines linker list loop looping loops map math matrix memory newbie news number output pointer problem program programming project python random read recursion recursive reference return rpg search simple sort spoonfeeding string strings struct temperature template templates text text-file tree url variable vector video visual visualstudio void win32 windows winsock wordfrequency wxwidgets






