Hi,
Could anyone explain to me why this works:

#include "stdafx.h"
#include <iostream>
using namespace std;
class A 
{
public: 
	A()
	{
		a = 0;
	}
	int a;
};
void change(A* source, A* destination)
{
	destination = source;
}
int _tmain(int argc, _TCHAR* argv[])
{
	A* ob1 = new A;
	ob1->a = 1;
	A* ob2 = new A;
	//ob2 = ob1; //THIS WORKS AS INTENDED
	//cout << ob2->a;
	change(ob1, ob2);//THIS DOESN'T
	cout << ob2->a;
	system("pause");
	return 0;
}
I completely do not understand this. 
Thank you

Recommended Answers

All 7 Replies

void change(A* source, A* destination)
{
    destination = source;
}

That doesn't do what its supposed to do. All it is doing is swapping pointer addresses and not the objects to which they point. Therefore that function is useless.

This is the correction: (Note: you may have to write a copy constructor for the class)

void change(A* source, A* destination)
{
    *destination = *source;
}

Thanks

But what about the line ob1 = ob2? this line outside of fnc works but inside doesn't. Why?

It doesn't work for the same reason that the change function doesn't work. *ob1 = *ob2; When you write ob1 = ob2 all that is doing is setting the address of ob1 to be the same as the address of ob2. You have to add the star to copy the object.

Due to Called by value arguments.
Value of pointer variables (an address) being copied at formal arguments. A new storage location will be create when the value of an actual argument is passed to a formal argument of method, and modification of the formal argument does not impact the actual argument.

Here is an example : Called by address.

void change1(A** source, A** destination)
{
  *destination = *source;
}

....
change1(&ob1, &ob2); // called (passed) by address

Here is an example : Called by address.

void change1(A** source, A** destination)
{
  *destination = *source;
}

....
change1(&ob1, &ob2); // called (passed) by address

That may or may not be the correct solution, depending on whether he wants to copy the address of the two objects (set the two addresses to be the same) or copy the class and leave the addresses unchanged.

If he wants to copy the addresses as your function does then he needs to delete the allocation for the destination parameter because your function will cause a memory leak.

Yes sir, I agree. Copy an address to the destination parameter will cause a memory leak.

and of course the following statements also causes a memory leak.

ob2 = ob1; //THIS WORKS AS INTENDED
cout << ob2->a;
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.