473,671 Members | 2,255 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Help overloading + and += simultaneously? ?

All:

The syntax for overloading the "+" and other simple binary math operators
is pretty straightforward , but I can't seem to wrap my brain around the
idea that overloading the "+" operator simultaneously overloads the "+="
operator.

Here's the problem I'm having with it:

When you overload a binary operator like "+", you accept two arguments and
you return a new object that holds the result. That's straightforward .

But if the overload of the "+" operator returns a *new* object, how can
that same overload be used to implement the "+=" operator, which is a
change to an *existing* object?

I just can't see how you can overload "+" and "+=" with the same code. Can
somebody help me understand this by pointing me to where this is
explained, or by explaining it to me?

Thanks.

--
John Hardin KA7OHZ ICQ#15735746 http://www.impsec.org/~jhardin/
jh*****@impsec. org FALaholic #11174 pgpk -a jh*****@impsec. org
key: 0xB8732E79 - 2D8C 34F4 6411 F507 136C AF76 D822 E6E6 B873 2E79
Nov 16 '05 #1
8 1349
"John Hardin" <jh*****@impsec .org> wrote in
news:pa******** *************** ***@impsec.org. ..
... if the overload of the "+" operator returns a *new* object, how can
that same overload be used to implement the "+=" operator, which is a
change to an *existing* object?


Probably the C# designers had primarily value types and immutable reference
types in mind. Take for examples:

string a,b;
a = b = "Test-String";
a += "Suffix";
Console.WriteLi ne("a = {0}, b = {1}", a,b);

or

int a,b;
a = b = 5;
a += 1;
Console.WriteLi ne("a = {0}, b = {1}", a,b);

In both cases "a" will be modified, but "b" will not.
C# will mimic exactly that behaviour if you override the "+" operator.

If you're used to C-style "p = &x; *p += 2;" statements, this might be
counter-intuitive, but if you're honest, that kind of code was always
error-prone, and got quite rare due to C#'s stricter type system anyway.

Niki
Nov 16 '05 #2
"John Hardin" <jh*****@impsec .org> wrote:
When you overload a binary operator like "+", you
accept two arguments and you return a new object
that holds the result. That's straightforward .
But if the overload of the "+" operator returns a *new*
object, how can that same overload be used to implement
the "+=" operator, which is a change to an *existing*
object?


Because a += b is just shorthand for a = a + b.

P.
Nov 16 '05 #3
On 27 Jun 2004 17:43, "John Hardin" wrote:
All:

The syntax for overloading the "+" and other simple binary math operators
is pretty straightforward , but I can't seem to wrap my brain around the
idea that overloading the "+" operator simultaneously overloads the "+="
operator.

Here's the problem I'm having with it:

When you overload a binary operator like "+", you accept two arguments and
you return a new object that holds the result. That's straightforward .

But if the overload of the "+" operator returns a *new* object, how can
that same overload be used to implement the "+=" operator, which is a
change to an *existing* object?

I just can't see how you can overload "+" and "+=" with the same code. Can
somebody help me understand this by pointing me to where this is
explained, or by explaining it to me?


Because '+=' is syntactic sugar: in other words is something that the
compiler takes in and translates to something else (just like properties)
before before spitting out the appropriate MSIL. If you write 'i += j'
what the compiler actually compiles is 'i = i + j' and thus the + operator
is on it's own. IIRC '++' does the same (I think...)

--
Simon Smith
simon dot s at ghytred dot com
www.ghytred.com/NewsLook - NNTP Client for Outlook
Nov 16 '05 #4
x++ and x+=1 and x=x+1 do amount to the same thing when compiled.

IL_000c: ldloc.0
IL_000d: ldc.i4.1
IL_000e: add
IL_000f: stloc.0

Each of those operations compile to exactly the same IL as seen above.

--
John Wood
EMail: first name, dot, second name at priorganize.com
"Simon Smith" <gh*****@commun ity.nospam> wrote in message
news:44******** *************** *******@ghytred .com...
On 27 Jun 2004 17:43, "John Hardin" wrote:
All:

The syntax for overloading the "+" and other simple binary math operators
is pretty straightforward , but I can't seem to wrap my brain around the
idea that overloading the "+" operator simultaneously overloads the "+="
operator.

Here's the problem I'm having with it:

When you overload a binary operator like "+", you accept two arguments andyou return a new object that holds the result. That's straightforward .

But if the overload of the "+" operator returns a *new* object, how can
that same overload be used to implement the "+=" operator, which is a
change to an *existing* object?

I just can't see how you can overload "+" and "+=" with the same code. Cansomebody help me understand this by pointing me to where this is
explained, or by explaining it to me?


Because '+=' is syntactic sugar: in other words is something that the
compiler takes in and translates to something else (just like properties)
before before spitting out the appropriate MSIL. If you write 'i += j'
what the compiler actually compiles is 'i = i + j' and thus the + operator
is on it's own. IIRC '++' does the same (I think...)

--
Simon Smith
simon dot s at ghytred dot com
www.ghytred.com/NewsLook - NNTP Client for Outlook

Nov 16 '05 #5
Simon Smith sez:
On 27 Jun 2004 17:43, "John Hardin" wrote:
I just can't see how you can overload "+" and "+=" with the same code.
Can somebody help me understand this by pointing me to where this is
explained, or by explaining it to me?


Because '+=' is syntactic sugar: in other words is something that the
compiler takes in and translates to something else (just like
properties) before before spitting out the appropriate MSIL. If you
write 'i += j' what the compiler actually compiles is 'i = i + j' and
thus the + operator is on it's own.


Thanks everybody who responded. It makes sense now.

Ouch. That means you have to be really careful overloading operators for
complex classes, and have to think carefully about precisely *what* you
mean by "+" and "+=" when designing classes.

For example, if you have a class with a single numeric property and
several non-numeric properties, you would need to copy all the non-numeric
properties to your new class in the overloaded "+" code lest they get
discarded - you can't distinguish between "a = a + b" and "a = b + c" at
runtime, can you?

Maybe operator overloading is just a Bad Idea for nontrivial classes...

--
John Hardin KA7OHZ ICQ#15735746 http://www.impsec.org/~jhardin/
jh*****@impsec. org FALaholic #11174 pgpk -a jh*****@impsec. org
key: 0xB8732E79 - 2D8C 34F4 6411 F507 136C AF76 D822 E6E6 B873 2E79

Nov 16 '05 #6
> x++ and x+=1 and x=x+1 do amount to the same thing when compiled.

IL_000c: ldloc.0
IL_000d: ldc.i4.1
IL_000e: add
IL_000f: stloc.0

Each of those operations compile to exactly the same IL as seen above.


That has nothing to do with it. The operator+ for primitive types is a
single opcode in IL (add), and for user-defined types it is a call to a
method called op_Addition(x, y).

--
cody

Freeware Tools, Games and Humour
http://www.deutronium.de.vu || http://www.deutronium.tk
Nov 16 '05 #7
> When you overload a binary operator like "+", you accept two arguments and
you return a new object that holds the result. That's straightforward .

But if the overload of the "+" operator returns a *new* object, how can
that same overload be used to implement the "+=" operator, which is a
change to an *existing* object?

The operator overloading in .NET seems very unready. Indeed, what you want
is currently not possible.
It is the same reason why the class StringBuilder does't support operator+=,
but the class string does.

--
cody

Freeware Tools, Games and Humour
http://www.deutronium.de.vu || http://www.deutronium.tk
Nov 16 '05 #8
"cody" <no************ ****@gmx.net> wrote in message
news:%2******** ********@TK2MSF TNGP12.phx.gbl. ..
x++ and x+=1 and x=x+1 do amount to the same thing when compiled.

IL_000c: ldloc.0
IL_000d: ldc.i4.1
IL_000e: add
IL_000f: stloc.0

Each of those operations compile to exactly the same IL as seen above.


That has nothing to do with it. The operator+ for primitive types is a
single opcode in IL (add), and for user-defined types it is a call to a
method called op_Addition(x, y).


Follow the thread man. The point here is that there is no difference between
the 3 addition operations above, which is what Simon was saying. Plus it's
interesting information, if you don't find it interesting don't comment!
Nov 16 '05 #9

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

17
4714
by: Terje Slettebø | last post by:
To round off my trilogy of "why"'s about PHP... :) If this subject have been discussed before, I'd appreciate a pointer to it. I again haven't found it in a search of the PHP groups. The PHP manual mentions "overloading" (http://no.php.net/manual/en/language.oop5.overloading.php), but it isn't really overloading at all... Not in the sense it's used in other languages supporting overloading (such as C++ and Java). As one of the...
12
1817
by: Joe | last post by:
Hi, Can I pass a "generic" class pointer as an argument to a function? For instance say classA and B are both derived from Z. { int iType =1;
4
1840
by: CoolPint | last post by:
I would be grateful if someone could point out if I am understanding correctly and suggest ways to improve. Sorry for the long message and I hope you will kindly bear with it. I have to make it elaborate to make sure my questions are clear enough. Let's say I need to write a function whose logic is same for all types (T) except in the case of T * (including const T *). Furtheremore , the function needs to be written differently for...
39
2192
by: zeus | last post by:
I know function overloading is not supported in C. I have a few questions about this: 1. Why? is it from technical reasons? if so, which? 2. why wasn't it introduced to the ANSI? 3. Is there any C implementation supporting this feature? I assume some of you will claim that there is no need in function overloading, so I would like to know your arguments too. Thanks,
4
6204
by: Madhu Gopinathan | last post by:
Hi All, I am faced with a horrible hang problem. I have a COM exe server that executes some tasks. The task execution manager is a thread that manages the pool of threads, which is 4 per processor. Each task is processed in a separate thread. Each of the executer threads is an STA thread, and it goes ahead and executes the task. No problems are encountered when tasks are executed one at a time, but when multiple tasks are executed...
17
2529
by: Student | last post by:
Hi All, I have an assignment for my Programming language project to create a compiler that takes a C++ file as input and translate it into the C file. Here I have to take care of inheritance and operator overloading and virtual functions. I mean it should not hamper the C++ meaning. In frank and simple terms i need to implement a small C++ compiler in C++, and i want the intermediate representation to be C. Please help me in this....
3
1216
by: AVL | last post by:
Hi, I need some info on text and xml files...... How many users can simultaneously read a text or xml file... I've a web appliaction which needs to access a text file and a xml file.. The current users of the system are around 1000 people...
2
2250
by: brzozo2 | last post by:
Hello, this program might look abit long, but it's pretty simple and easy to follow. What it does is read from a file, outputs the contents to screen, and then writes them to a different file. It uses map<and heavy overloading. The problem is, the output file differs from input, and for the love of me I can't figure out why ;p #include <iostream> #include <fstream> #include <sstream>
35
2049
by: josh | last post by:
Hi, I coded the following but It does not return what I expect, why? #include <iostream> using namespace std; class Other { public: int i;
0
8476
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8393
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8914
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
5695
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4224
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4406
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2810
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
2051
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
2
1809
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.