class panda {
int a;
public:
panda(int x)
{
a = x;
}
friend ostream& operator<<(ostream& stream, panda ob)
{
stream << ob.a;
return stream;
}
};
Given that class, now see these statements-
1 2 3
cout << panda(420) << endl; // prints 420
cout << new panda(420) << endl; // prints an address
cout << *(new panda(420)) << endl; // prints 420
I tried different things and found the above results.
Now what is actually happening on those three statements? Can someone explain please?
And the first statement- cout << panda(420) << endl;, should we also call it dynamic allocation?
panda(420), is just initialisation, which is normal.
I think what's happening with the second is that new is returning a pointer as that is the point of new. You should have a pointer and set it to new panda(420) panda* pandaPtr = new panda(420)
Btw, that is dynamic allocation because you are dynamically allocated some memory for that variable.
As new panda(420) is returning a pointer, when you dereference it, it produces the correct value. Also, the second and third statements leak memory because you aren't storing where the panda was allocated so you could delete it later, just thought I should point that out.
Lastly, I might be wrong about new returning a pointer, it might return an address, but it is easiest to think about it returning a pointer.
Now what is actually happening on those three statements?
1) A temporary is created, then user defined operator is applied. After it ends, temporary is destroyed.
2) An unnamed object is created in dynamic memory. As new returns pointer, and overload of << operator for pointers prints address contained in it, this is happens. As we do not store pointer anywhere, it is lost, and we cannot delete object. Memory leaked.
3) An unnamed object is created in dynamic memory. New returns pointer, but we dereference it immideatly returning a reference to that object. User defined operator is applied. After this we lose pointer to object too, so memory is leaked.
Object with automatic storage is destroyed when its scope ends
In first example ( cout << panda(420) << endl; ) it is destroyed when function which uses it ( operator<< ) ends.
In second example ( panda ob = panda(420); ) it is destroyed when current code block ends
1 2 3 4
{
panda ob = panda(420);
//...
} // ob is destroyed here