What happens to the object returned from the last line of following code
class weight
{
int kilogram;
int gram;
public:
void getdata ();
void putdata ();
void sum_weight (weight,weight) ;
weight sum_weight (weight) ;
};
weight weight :: sum_weight(weight w2)
{
weight temp;
temp.gram = gram + w2.gram;
temp.kilogram=temp.gram/1000;
temp.gram=temp.gram%1000;
temp.kilogram+=kilogram+w2.kilogram;
return(temp);
}
int main(){
//.....//
w3=w2.sum_weight(w1);
w2.sum_weight(w1);
//.....//
}
Does it remains in the memory till completion or it gets deleted.
Let's try to look at what actually happens:
#include <stdio.h>
class A {
public:
A() { printf("default constructing at %016zx\n", (size_t)this); }
A(const A& a) { printf("copy constructing from %016zx at %016zx\n", (size_t)&a, (size_t)this); }
void operator=(const A& a) { printf("assigning from %016zx to %016zx\n", (size_t)&a, (size_t)this); }
~A() { printf("destructing at %016zx\n", (size_t)this); }
static A makeA() {
A temp;
return temp;
}
};
int main() {
A a;
printf("calling makeA()\n");
a = A::makeA();
printf("returned from makeA()\n");
}
This code produces the following output on my machine (no compiler optimizations!):
default constructing at 00007ffe39415d0e
calling makeA()
default constructing at 00007ffe39415d0f
assigning from 00007ffe39415d0f to 00007ffe39415d0e
destructing at 00007ffe39415d0f
returned from makeA()
destructing at 00007ffe39415d0e
So, you see, during the call the variable in makeA()
is created, the value of the variable in makeA()
is assigned to the variable in main()
, and the variable in makeA()
is destroyed. The variable in main()
is created before the call and remains valid until main()
returns to its caller.