|
-
February 19th, 2010, 11:32 AM
#1
Simple Question: Pointers as Arguments
Hello,
If I pass a pointer to an object, as an argument to a function, then if the object pointed to by the pointer is modified by the function, will this modification affect the original object? I originally thought that the answer would be yes, but executing the code below suggests no.
Code:
class MyClass
{
public:
int x, y;
MyClass(){x = 1, y = 2;};
};
void MyFunction(MyClass* an_object)
{
an_object = new MyClass();
an_object->x = 5;
an_object->y = 6;
};
int main()
{
MyClass* my_object = new MyClass();
MyFunction(my_object);
return 0;
}
Here, the MyFunction() does not change the values of x and y of the object in the main function. The values remain at x = 1 and y = 2.
Why is this? When I pass a pointer to an object to MyFunction(), then a new object is created and is pointed to by this same pointer. Thus, any modifications to this new object should affect the original object. But this is not so!
Thanks
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|