Consider the following code:

const int con = 100;

int &ref1 = 10;   //Where is this 10 stored?
int &ref2 = con;

ref1 = 20;
ref2 = 90;

cout<<ref1<<con<<ref2;

This outputs: 20 100 90

My only queries are:

a) Where is the hard coded number 10 stored?
b) When ref1 is modified which memory was modified? (10's or ref1 has it's own memory)
c) Why was const variable not modified but somehow it's reference was?

Regards,
Nisheeth Barthwal

How did you get this to even compile? I don't think either of those initializations is even legal.

Long Live Borland! This thing had me baffled as much as you.

A query however, the hard-coded numbers are *not* stored in the memory right? I mean the assembly form can just be:

mov ax,10

& not

.data
foo db 10
.code
mov ax,foo

A query however, the hard-coded numbers are *not* stored in the memory right? I mean the assembly form can just be:

mov ax,10

& not

.data
foo db 10
.code
mov ax,foo

Actually, as I understand it, they generate temporaries that are used by the operator function associated with the assignment operator.

Sorry if I misunderstood but did you affirm that "temporary memory locations" are created upon their assignment? What about their lifetime? Are they disposed of as soon as the assignment is completed.
If a temporary is created it should correspond to it being defined (db) in the message part right? Or it's just the case of it being hard coded in the assembly as well. (mov ax,10)

Thank you for your concern.

Sorry if I misunderstood but did you affirm that "temporary memory locations" are created upon their assignment? What about their lifetime? Are they disposed of as soon as the assignment is completed.
If a temporary is created it should correspond to it being defined (db) in the message part right? Or it's just the case of it being hard coded in the assembly as well. (mov ax,10)

Thank you for your concern.

I don't know assembly, so I can't answer your questions concerning that.

But, again, as I understand things (which means I could be mistaken), when you invoke an operator, you are actually calling an "operator function". This is why you can write overloaded operators, they're nothing more than function overloads. I would expect the temporaries to have a lifetime defined by the scope of that operator function.

If you have a class, let's call it Example, with an overloaded assignment operator, the definition of the operator will be:

Example & operator= (const Example & other) {
  if (this != &other) {  //check the pointers to prevent self-assignment
    this->aMember = other.aMember;
    this->aMember = other.aMember;
    /* ... etc. ... */
  }
 return *this;
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.