Gurikar wrote:
HI,
class A()
{
private:
int i;
char c;
public:
A();
};
void fun(A* a)
{
a = new A(); //allocated on heap(2nd time allocation)
}
int main()
{
A a; // allocated on stack
fun(&a);
}
Can you please tell wheather memory gets allocated 2 times for object
A(one on stack other on heap).
No.
Is this a valid code.
Yes.
Does both have same adress(pointing to memory, even though both are on
different memory)..
No.
Atleast tell whats wrong in this code??
Just remember that passing a parameter to a function means that its value
gets copied into the function parameter (unless you pass a reference).
In main, you take the address of a. Then you call fun and pass that address
to it. Fun has a parameter 'a' that this address gets copied into. So fun
now works on a local copy of the pointer value. Any changes to it will only
affect that copy within the function.
The next thing is that you assign to that parameter the return value from
'new A()', which is a pointer to a fresh object of class A. When returning
from the function, the parameter a is destroyed (but not the object it's
pointing to). Since 'a' within foo was just a local copy, nothing has
changed outside the function.
But now you have an object allocated with new, and you lost the only pointer
to it that you had when the function returned. You can never delete the
object anymore.