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 :)
Re: Simple Question: Pointers as Arguments
Quote:
Originally Posted by
karnavor
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?
Because you overwrite the pointer with a pointer to a newly allocated object.
Quote:
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!
No, you create 2 instance of MyClass in your application. First you create one in main and then pass a pointer to that object to MyFunction. In that function you create the second instance and store a pointer to that instance in the function argument. When you do that, you've lost the pointer to the instance created in main.
Re: Simple Question: Pointers as Arguments
Quote:
Originally Posted by
karnavor
When I pass a pointer to an object to MyFunction(), then a new object is created and is pointed to by this same pointer.
Note that an_object is not a pointer. It's a pointer variable. It holds a pointer. It will hold the pointer until you assign a new pointer to it.
It's considered bad style to "reuse" parameter variables within a function. It's best to declare them const so they cannot be modified. This makes the code less error-prone.
Re: Simple Question: Pointers as Arguments
Quote:
Originally Posted by nuzzle
Note that an_object is not a pointer. It's a pointer variable. It holds a pointer. It will hold the pointer until you assign a new pointer to it.
I prefer to say that an_object is a pointer, as a pointer is an object whose value is an address. Consequently, this pointer will hold the address until a new address is assigned to it. The important part here is to recognise that it is a variable, but to say that it is not a pointer, although true by one possible interpretation, can be confusing since it would commonly be called a pointer.
Re: Simple Question: Pointers as Arguments
Quote:
Originally Posted by
laserlight
I prefer to say that an_object is a pointer, as a pointer is an object whose value is an address. Consequently, this pointer will hold the address until a new address is assigned to it. The important part here is to recognise that it is a variable, but to say that it is not a pointer, although true by one possible interpretation, can be confusing since it would commonly be called a pointer.
Well, you're probably correct. In C++ pointer means pointer variable.
Still I feel the OP may have missed the "variable nature of a pointer".
Re: Simple Question: Pointers as Arguments
In my opinion this is a very common mistake, maybe it's caused by call-by-value and call-by-reference nomenclature. In a way K&R style tell more what's going on i.e:
Code:
void DoSome()
int* someExternalInt;
int someExternalIntSize; // Very bad name
)
{
...
someThingElse = 3:
*someExternalInt = someThingElse;
someExternalInt++;
*someExternalInt = ++someThingElse;
...
}
What am i trying to say? Well it's that all parameters to a function is like local variables. The only difference between those declared in the function header an those declared in the function is that the former are initialized by the caller. I.e. feel free to modify the parameters to a function as you like as long as you know what your're doing. I.e someExternalInt++ is ok since that wont affect caller a bit since the pointer he's provided is a copy.
Ok, think I need claim some "be easy on me" for this post. This is after friday dinner after some wine.... life's good though :)
Re: Simple Question: Pointers as Arguments
Quote:
Originally Posted by
S_M_A
In my opinion this is a very common mistake, maybe it's caused by call-by-value and call-by-reference nomenclature. In a way K&R style tell more what's going on i.e:
Code:
void DoSome()
int* someExternalInt;
int someExternalIntSize; // Very bad name
)
{
...
someThingElse = 3:
*someExternalInt = someThingElse;
someExternalInt++;
*someExternalInt = ++someThingElse;
...
}
What am i trying to say? Well it's that all parameters to a function is like local variables. The only difference between those declared in the function header an those declared in the function is that the former are initialized by the caller. I.e. feel free to modify the parameters to a function as you like as long as you know what your're doing. I.e someExternalInt++ is ok since that wont affect caller a bit since the pointer he's provided is a copy.
Ok, think I need claim some "be easy on me" for this post. This is after friday dinner after some wine.... life's good though :)
Haha you must be drunk with happiness, now give me your bong!
Re: Simple Question: Pointers as Arguments
Well, "pointer variable" or "pointer" - this is a question of terminology.
We are taking this discussion a bit away from what the OP asked, but here's how I see it (the pointer related terminology, that is):
Type* name,
or as some prefer
Type *name,
is a declaration of a pointer called "name", which points to data of the type "Type", by storing its memory address as its value (so, in this regard, "pointer" and "pointer variable" are synonymous).
The value of the pointer (or the value stored by it) is the memory address, and the data pointed by it is the data on that address (so in my opinion it is wrong to call this data a "pointer".)
P.S. To OP: If you, in this somewhat off topic discussion, lost track of what they told you to do - just delete the first line of code in MyFunction(...).
Re: Simple Question: Pointers as Arguments
P.P.S. I use C# now, where pointers are sort of banished (only allowed in an unsafe context), but I like the "Type* name" notation better; the reasoning behind it is:
SomeClass ==> type called "SomeClass"
SomeClass* ==> type called "SomeClass-pointer" or "pointer to SomeClass"
Re: Simple Question: Pointers as Arguments
Quote:
Originally Posted by
TheGreatCthulhu
P.P.S. I use C# now, where pointers are sort of banished
I'm not familiar with C#, but I've heard it's similar to Java; and in Java, from a C++ coder's perspective everything except primitives are pointers. They call them "references", but in terms of their semantics, they have more in common with C++ pointers than C++ references. I suspect C# is similar in that regard.
Re: Simple Question: Pointers as Arguments
Quote:
Originally Posted by
Lindley
I'm not familiar with C#, but I've heard it's similar to Java; and in Java, from a C++ coder's perspective everything except primitives are pointers. They call them "references", but in terms of their semantics, they have more in common with C++ pointers than C++ references. I suspect C# is similar in that regard.
I learned Java before C++ so I'm still influenced with that terminology. A Java reference would correspond to a C++ address. And a Java reference variable would correspond to a C++ pointer.
Re: Simple Question: Pointers as Arguments
Quote:
Originally Posted by
TheGreatCthulhu
Well, "pointer variable" or "pointer" - this is a question of terminology.
I haven't thought about it before but after checking the C++ standard the term "pointer variable" is never used so I guess one could say that such a thing doesn't exist.
Re: Simple Question: Pointers as Arguments
Quote:
Originally Posted by
TheGreatCthulhu
P.P.S. I use C# now, where pointers are sort of banished (only allowed in an unsafe context), but I like the "Type* name" notation better; the reasoning behind it is:
SomeClass ==> type called "SomeClass"
SomeClass* ==> type called "SomeClass-pointer" or "pointer to SomeClass"
But that notation leads to the following famous example:
Code:
Type* a, b, c; // a, b, and c expected to be of type Type*; in actuality, only a is a pointer.
Re: Simple Question: Pointers as Arguments
Quote:
Originally Posted by
Lindley
I'm not familiar with C#, but I've heard it's similar to Java; and in Java, from a C++ coder's perspective everything except primitives are pointers. They call them "references", but in terms of their semantics, they have more in common with C++ pointers than C++ references. I suspect C# is similar in that regard.
Yes, C# references (or "reference types") are a concept similar to pointers, but the difference is that, references are, under the hood, actually objects used by the automated memory management system of the .NET runtime.
Sort of "extended" or "smart" pointers. And reference types are always passed by reference (although the references themselves are passed by value by default). I guess C# "value types" (structs) would roughly correspond to Java's primitive types (at least in the way they are passed to a method), but there are some differences.
P.S. I think the creation of C# was, in fact, influenced by Java.
Re: Simple Question: Pointers as Arguments
Quote:
Originally Posted by
standard
But that notation leads to the following famous example:
Code:
Type* a, b, c; // a, b, and c expected to be of type Type*; in actuality, only a is a pointer.
Really?! I'm not using C++ for a while now, so I'm a bit rusty on such intricacies. :blush:
Interesting - although I don't like this standard (makes my reasoning fail, or at least seem awkward); but, this is well established, so it is certainly something for a programmer to bear in mind.
Thanks for the heads up.
Re: Simple Question: Pointers as Arguments
Quote:
Originally Posted by
TheGreatCthulhu
P.S. I think the creation of C# was, in fact, influenced by Java.
Many would rather have it that C# is a rip-off of Java. :)
Back in 1995 when Java was introduced by Sun everybody was behind Java including Microsoft and Apple. Steven Jobs bragged that Apple would have the best Java on the planet while Microsoft actually had it.
Then the relationship between Sun and Microsoft turned sour. The reason was that Microsoft wanted to tweak Java so that programs compiled with the Microsoft compiler would run on Windows only. This developed into an ugly legal war that ended with Microsoft dropping Java and later paying damages to Sun.
Instead Microsoft came up with C# that initially was more or less a Java clone. But over the years lots of new features were introduced in C# unlike Java which pretty much stayed the same. So today they differ quite a lot apart from the fact that both are based on the same general principles.
Re: Simple Question: Pointers as Arguments
About multiple pointer declarations - I think I remember now I have read about it long time ago.
Anyway, here's the source of confusion - this is from MSDN article called "Pointer types (C# Programming Guide) ":
Code:
int* p1, p2, p3; // Ok
int *p1, *p2, *p3; // Invalid in C#
What I don't like in the standard used by C++ is that a token *name has a different meaning in different contexts (it means "pointer" in a declaration, and "value pointed by" otherwise). It's not a major issue, but it can lead to some unnecessary confusion.
To nuzzle:
So the story behind Java and C# is a sort of a legal soap opera. Funny :) :) :)
But C# turned out rather good, and I love it.
P.S. Oh God, I just tried to CTRL+SPACE a word here.
Re: Simple Question: Pointers as Arguments
One more thing: shouldn't karnavor's MyFunction(...) as it is defined in the first post also cause a memory leak? Once the function exits, the newly created data is lost; since, although the data is passed by reference, the pointer itself is passed by value, right?
Re: Simple Question: Pointers as Arguments
Quote:
Originally Posted by
TheGreatCthulhu
To nuzzle:
So the story behind Java and C# is a sort of a legal soap opera. Funny :) :) :)
But C# turned out rather good, and I love it.
For many it was a matter of life or death. This happened at the height of Microsoft bashing and Sun was considered the good white knight in shining armour standing up to Microsoft, the very incarnation of everything evil on earth. So when Sun took the money and made up with Microsoft emotions boiled over. Many just couldn't stand the sight of Scott McNeally shaking hands with Bill Gates, smiling as if they were longtime buddies. Some high-ranking Sun employees felt so betrayed they even left the company. I have a feeling this may have contributed substantially to Sun's downfall.
Anyway, I prefer Java for the simple reason it's portable. C# is more advanced today but unfortunately it's limited to Windows. There's an interesting alternative to both Java and C# and that's C++/CLI. If it was ported to the Java VM it probably would be my favourite. C++/CLI basically is classic C++ with the "managed" features of Java and C# on top.
Everything considered, my favourite is C++. Especially with Qt now licenced under LGPL and especially with the new features of the new standard coming soon.
Re: Simple Question: Pointers as Arguments
Quote:
Originally Posted by TheGreatCthulhu
Interesting - although I don't like this standard (makes my reasoning fail, or at least seem awkward); but, this is well established, so it is certainly something for a programmer to bear in mind.
It is mentioned in Stroustrup's answer to the FAQ: Is ``int* p;'' right or is ``int *p;'' right?
Re: Simple Question: Pointers as Arguments
Quote:
Originally Posted by
nuzzle
Anyway, I prefer Java for the simple reason it's portable. C# is more advanced today but unfortunately it's limited to Windows.
Well, there's Mono, but that's pretty much a hack to get .NET running on non-Windows systems, not true cross-platform capability.
Quote:
There's an interesting alternative to both Java and C# and that's C++/CLI. If it was ported to the Java VM it probably would be my favourite. C++/CLI basically is classic C++ with the "managed" features of Java and C# on top.
That's surprising. Again, I haven't had reason to familiarize myself with .NET at all yet, but the general consensus seemed to be that C++/CLI was a kludged-together Frankenstein which does neither .NET nor native coding very well, while trying to do both.
Re: Simple Question: Pointers as Arguments
Quote:
Originally Posted by
laserlight
Thanks for that.
Stroustrup's site is like a programmer's bible, everyone should have it bookmarked (Bjarne Stroustrup's homepage).
I followed your link the day you posted it, but I didn't intend to write any new posts, however now I feel that I should share this, since novice programmers, but not just them, could greatly benefit from it. Especially C++ programmers.
Quote:
Originally Posted by
nuzzle
Everything considered, my favourite is C++. Especially [...] with the new features of the new standard coming soon.
You mean C++0x?
Interesting. Check out what Stroustrup says on the same site: "Surprisingly, C++0x feels like a new language".
(Bjarne Stroustrup's C++0x FAQ: What do you think of C++0x?)