CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Page 1 of 2 12 LastLast
Results 1 to 15 of 22
  1. #1
    Join Date
    Aug 2009
    Posts
    68

    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

  2. #2
    Join Date
    Jul 2005
    Location
    Netherlands
    Posts
    2,042

    Re: Simple Question: Pointers as Arguments

    Quote Originally Posted by karnavor View Post
    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.
    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.
    Cheers, D Drmmr

    Please put [code][/code] tags around your code to preserve indentation and make it more readable.

    As long as man ascribes to himself what is merely a posibility, he will not work for the attainment of it. - P. D. Ouspensky

  3. #3
    Join Date
    May 2009
    Posts
    2,413

    Re: Simple Question: Pointers as Arguments

    Quote Originally Posted by karnavor View Post
    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.

  4. #4
    Join Date
    Jan 2006
    Location
    Singapore
    Posts
    6,765

    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.
    Last edited by laserlight; February 19th, 2010 at 01:31 PM.
    C + C++ Compiler: MinGW port of GCC
    Build + Version Control System: SCons + Bazaar

    Look up a C/C++ Reference and learn How To Ask Questions The Smart Way
    Kindly rate my posts if you found them useful

  5. #5
    Join Date
    May 2009
    Posts
    2,413

    Re: Simple Question: Pointers as Arguments

    Quote Originally Posted by laserlight View Post
    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".

  6. #6
    Join Date
    Oct 2006
    Location
    Sweden
    Posts
    3,654

    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
    Last edited by S_M_A; February 19th, 2010 at 05:18 PM.
    Debugging is twice as hard as writing the code in the first place.
    Therefore, if you write the code as cleverly as possible, you are, by
    definition, not smart enough to debug it.
    - Brian W. Kernighan

    To enhance your chance's of getting an answer be sure to read
    http://www.codeguru.com/forum/announ...nouncementid=6
    and http://www.codeguru.com/forum/showthread.php?t=366302 before posting

    Refresh your memory on formatting tags here
    http://www.codeguru.com/forum/misc.php?do=bbcode

    Get your free MS compiler here
    https://visualstudio.microsoft.com/vs

  7. #7
    Join Date
    Jan 2008
    Location
    California, USA
    Posts
    822

    Re: Simple Question: Pointers as Arguments

    Quote Originally Posted by S_M_A View Post
    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!

  8. #8
    Join Date
    Jan 2010
    Posts
    1,133

    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(...).

  9. #9
    Join Date
    Jan 2010
    Posts
    1,133

    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"

  10. #10
    Lindley is offline Elite Member Power Poster
    Join Date
    Oct 2007
    Location
    Seattle, WA
    Posts
    10,895

    Re: Simple Question: Pointers as Arguments

    Quote Originally Posted by TheGreatCthulhu View Post
    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.

  11. #11
    Join Date
    May 2009
    Posts
    2,413

    Re: Simple Question: Pointers as Arguments

    Quote Originally Posted by Lindley View Post
    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.
    Last edited by nuzzle; February 20th, 2010 at 02:49 AM.

  12. #12
    Join Date
    May 2009
    Posts
    2,413

    Re: Simple Question: Pointers as Arguments

    Quote Originally Posted by TheGreatCthulhu View Post
    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.

  13. #13
    Join Date
    Feb 2010
    Posts
    4

    Re: Simple Question: Pointers as Arguments

    Quote Originally Posted by TheGreatCthulhu View Post
    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.

  14. #14
    Join Date
    Jan 2010
    Posts
    1,133

    Re: Simple Question: Pointers as Arguments

    Quote Originally Posted by Lindley View Post
    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.

  15. #15
    Join Date
    Jan 2010
    Posts
    1,133

    Re: Simple Question: Pointers as Arguments

    Quote Originally Posted by standard View Post
    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.

    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.

Page 1 of 2 12 LastLast

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured