Jump to content

  • Log In with Google      Sign In   
  • Create Account


Can you return a class member object as a pointer?


Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.

  • You cannot reply to this topic
19 replies to this topic

#1 AussieSpoon   Members   -  Reputation: 184

Like
0Likes
Like

Posted 06 January 2013 - 11:21 PM

This may sound stupid (I'm pretty sure you can't) but I'm wondering if I have: 

 

class a {}

class b
{
public: 
    
    a GetA(){return MyObject;}

private:

    a MyObject;
};

 

Instead of GetA() returning MyObject as an object is it possible to return it as a pointer(*)?

 

Thanks



Sponsor:

#2 Hodgman   Moderators   -  Reputation: 29510

Like
6Likes
Like

Posted 06 January 2013 - 11:28 PM

Yes.

 

As a pointer:

a* GetA() {return &MyObject;}

MyB.GetA()->DoSomethingToMyObject();

 

or as a reference:

a& GetA(){return MyObject;}

MyB.GetA().DoSomethingToMyObject();


Edited by Hodgman, 06 January 2013 - 11:29 PM.


#3 Álvaro   Crossbones+   -  Reputation: 12923

Like
7Likes
Like

Posted 07 January 2013 - 12:19 AM

Returning a pointer or a reference to internal class data is of course valid, but one has to be careful not to use the pointer or reference if the object is destroyed.

 

a *my_a_pointer;
{
  b my_b;
  my_a_pointer = b.GetA();
}
my_a_pointer->DoSomethingToMyObject(); // <-- Trouble! my_b has been destroyed already

 

This is not too different from what happens when you obtain a char const * from a string using std::c_str(). But it's still worth mentioning.



#4 Mercurialol   Members   -  Reputation: 221

Like
-1Likes
Like

Posted 07 January 2013 - 01:50 AM

What does pointer contain as a VALUE? An address. Therefore - just return the address.



#5 Khatharr   Crossbones+   -  Reputation: 2963

Like
4Likes
Like

Posted 07 January 2013 - 02:24 AM

 Can you return a class member object as a pointer?

Did you ask the compiler?
void hurrrrrrrr() {__asm sub [ebp+4],5;}

There are ten kinds of people in this world: those who understand binary and those who don't.

#6 larspensjo   Members   -  Reputation: 1526

Like
0Likes
Like

Posted 07 January 2013 - 02:52 AM

If you want to return a reference to the class member, I suppose the reason is that you want to modify the member. But if the reason is that the object is big, and you want to improve performance by not having to return a copy, it may be a good idea to return a const pointer to the object, or const reference.

 

Returning a pointer (const or not) is valid C++, but it violates some principles of object oriented programming. If you want the object updated, the usual principle to have the update logic in a member function instead.

 

To expose internal design of a class to the outside is usually a bad idea. That means you have an extra dependency, and dependencies should be kept to a minimum. Suppose you later find out that the data need to be managed in another way, you can no longer update only the class 'b'. You will also have to find all users of GetA(), and update them. If it is a library, it may not be possible, and the API is suddenly incompatible.


Current project: Ephenation.
Sharing OpenGL experiences: http://ephenationopengl.blogspot.com/

#7 Olof Hedman   Crossbones+   -  Reputation: 2752

Like
4Likes
Like

Posted 07 January 2013 - 04:21 AM

Maybe I'm nitpicky, but isn't it a bit wrong (and slightly confusing) to say that you "return an object as a pointer"?

Too me, that doesn't really make sense.
What you do is "returning a pointer that points to the object".

The pointer itself is an object too, a very different object then the class object it (maybe) points to.
I think that remembering this makes the answer more obvious.

But again, I'm not even a native english speaker, so maybe I read too much into the grammar....

Edited by Olof Hedman, 07 January 2013 - 04:22 AM.


#8 Geometrian   Crossbones+   -  Reputation: 1495

Like
-2Likes
Like

Posted 07 January 2013 - 10:15 AM

Maybe I'm nitpicky, but isn't it a bit wrong (and slightly confusing) to say that you "return an object as a pointer"?

Too me, that doesn't really make sense.
What you do is "returning a pointer that points to the object".

The pointer itself is an object too, a very different object then the class object it (maybe) points to.
I think that remembering this makes the answer more obvious.

This is an excellent point. And, while OT, another important one: people will talk about pass-by-value/pass-by-reference. in C/C++, everything is pass-by-value; it's just that sometimes, you pass values that are pointers, so the objects they represent don't copy.


And a Unix user said rm -rf *.* and all was null and void...|There's no place like 127.0.0.1|The Application "Programmer" has unexpectedly quit. An error of type A.M. has occurred.

#9 rip-off   Moderators   -  Reputation: 8120

Like
4Likes
Like

Posted 07 January 2013 - 11:30 AM

in C/C++, everything is pass-by-value...

Please identify the value is being passed in the following code:

void frobnicate(int &example) {
    example = 42;
}



#10 BeerNutts   Crossbones+   -  Reputation: 2815

Like
0Likes
Like

Posted 07 January 2013 - 10:42 PM

 

in C/C++, everything is pass-by-value...

 

 

Please identify the value is being passed in the following code:

 

void frobnicate(int &example) {
    example = 42;
}

I suppose he would've been correct if he said, "In C, everything is passed by value...."

 

But, not so for C++, as you point out.


My Gamedev Journal: 2D Game Making, the Easy Way

---(Old Blog, still has good info): 2dGameMaking
-----
"No one ever posts on that message board; it's too crowded." - Yoga Berra (sorta)

#11 Geometrian   Crossbones+   -  Reputation: 1495

Like
-1Likes
Like

Posted 08 January 2013 - 05:30 PM

I suppose he would've been correct if he said, "In C, everything is passed by value...."
While this is what I meant to say, I'm still not technically wrong.
 
Please identify the value is being passed in the following code:
void frobnicate(int &example) {
    example = 42;
}


When the compiler creates a function like this (and assuming it doesn't inline it), it needs to be able to change the value of that variable within the function. The C++ specification deliberately says that the actual way this happens is implementation defined, and that whether a reference actually uses storage or not is unspecified.

In some implementations, this is just a pointer, which means that yes, the value of the pointer is passed onto the stack. In this case, the "reference" semantics C++ gives you are nothing more than syntactic sugar with extra compile-time checking. Under the hood, it's nothing more than your standard raw pointer.

Sometimes you can't get around doing that unless you want to write better algorithms. Some compilers don't bother. Mine doesn't.

Edited by Geometrian, 08 January 2013 - 05:40 PM.

And a Unix user said rm -rf *.* and all was null and void...|There's no place like 127.0.0.1|The Application "Programmer" has unexpectedly quit. An error of type A.M. has occurred.

#12 Brother Bob   Moderators   -  Reputation: 8040

Like
2Likes
Like

Posted 08 January 2013 - 05:45 PM

When the compiler creates a function like this (and assuming it doesn't inline it), it needs to be able to change the value of that variable within the function. The C++ specification deliberately says that the actual way this happens is implementation defined, and that whether a reference actually uses storage or not is unspecified.


In some implementations, this is just a pointer, which means that yes, the value of the pointer is passed onto the stack. In this case, the "reference" semantics C++ gives you are nothing more than syntactic sugar with extra compile-time checking. Under the hood, it's nothing more than your standard raw pointer.

Sometimes you can't get around doing that unless you want to write better algorithms. Some compilers don't bother. Mine doesn't.

Don't confuse language concepts and implementation details. The fact that it is a pointer "under the hood" is, as you say, an implementation detail, but it is not a pointer being passed by value as far as the language is concerned; it is passed by reference.

 

If you bring implementation details and "under the hood" into the picture, then nothing exists in any language, because it all boils down to machine code being executed in one way or another, and machine code typically has no templates, no structures, no functions, no scope, no name spaces, no closures, no typing... nothing. A language just abstract such things so that the programmer can write code what the program is supposed to do, and the compiler/virtual machine/whatever ensures that the program is actually doing just that on the particular computer running it.



#13 Geometrian   Crossbones+   -  Reputation: 1495

Like
-2Likes
Like

Posted 08 January 2013 - 06:35 PM

Don't confuse language concepts and implementation details. The fact that it is a pointer "under the hood" is, as you say, an implementation detail, but it is not a pointer being passed by value as far as the language is concerned; it is passed by reference.

Actually, my bringing in of implementation details was to cement that references may in fact be pointers--for the sake of showing that my argument holds in actual architectural-level practice.

As far as your distinction, I think (in this case) it's a distinction without a difference. I will agree that references and pointers have a few semantic differences (for example, you can do arithmetic on pointers, and (so) references can do more checking), but really there's no difference between them. They act the same way, and you can use one instead of the other with almost equal facility.

 

For purposes of this discussion, the key point is that passing references into functions works in the same way as passing pointers. In the above example, the answer is "the reference int&example is passed by value, since its value is copied"--nevermind that that copying might be optimized away, just as inlining might similarly be able to optimize away other copies for pointers. Semantically thinking of the reference being copied doesn't break anything, and is actually closer to truth in practice.

 

If you bring implementation details and "under the hood" into the picture, then nothing exists in any language, because it all boils down to machine code being executed in one way or another, and machine code typically has no templates, no structures, no functions, no scope, no name spaces, no closures, no typing... nothing. A language just abstract such things so that the programmer can write code what the program is supposed to do, and the compiler/virtual machine/whatever ensures that the program is actually doing just that on the particular computer running it.

Reducto ad absurdum, but still somewhat relevant. Machine code has comparably few features, I'll agree, but in this case, the idea of "pointer"s actually exists, albeit not with static checks.

And I completely agree that whether "references" are implemented at the machine level through pointers or at the compiler level through optimizations, the point is that they exist in C++, which abstracts it. However, the converse of that was never my point; as above, I brought in implementation details to show how it works in practice. I had intended the first main paragraph of my last post to address that.

The point with all this is that the (key) properties of "references" exactly mirror those of pointers: they are datatypes held in variables, and they get copied by value when they are passed into functions, just as much as pointers. That's the functionality that C++ exposes and abstracts for us. C++ programmers might not think about it that way, since in the ideal case, they can be optimized just like any other code. But as we've agreed, that last is an implementation detail.


Edited by Geometrian, 08 January 2013 - 06:37 PM.

And a Unix user said rm -rf *.* and all was null and void...|There's no place like 127.0.0.1|The Application "Programmer" has unexpectedly quit. An error of type A.M. has occurred.

#14 Álvaro   Crossbones+   -  Reputation: 12923

Like
0Likes
Like

Posted 08 January 2013 - 06:53 PM

I knew assembly language (Z80 and x86) before I learned C, and it was trivial to think of a natural assembly implementation of most things in C. When I was learning C++, I wouldn't consider that I understood a feature unless I had some idea of how that would be implemented in assembly. In particular, thinking of references as memory addresses with slightly different syntax than pointers was very helpful to me.

 

On a side note, I still don't think I truly understand exceptions, in that sense: I should probably spend a couple of hours figuring it out.



#15 Paradigm Shifter   Crossbones+   -  Reputation: 5255

Like
0Likes
Like

Posted 08 January 2013 - 06:56 PM

You can sort of do exceptions in C with setjmp/longjmp. That's how SSE is done in Windows.
"Most people think, great God will come from the sky, take away everything, and make everybody feel high" - Bob Marley

#16 Hodgman   Moderators   -  Reputation: 29510

Like
0Likes
Like

Posted 08 January 2013 - 07:02 PM

You can sort of do exceptions in C with setjmp/longjmp. That's how SSE is done in Windows.

*SEH wink.png 

 

On a side note, I still don't think I truly understand exceptions, in that sense: I should probably spend a couple of hours figuring it out.

They key part of C++ exceptions (as opposed to SEH/setjmp/longjmp type ones) is that stack-unwinding takes place. I learnt a lot about this by writing a stack-allocator that supports unwinding (calling destructors of things in the stack in the opposite order to creation).



#17 Paradigm Shifter   Crossbones+   -  Reputation: 5255

Like
0Likes
Like

Posted 08 January 2013 - 07:06 PM

Yeah, I meant SEH, but I have had several cans of Lidl's finest cheapest ales ;)<br /><br />Stack unwinding is the big difference, yeah.
"Most people think, great God will come from the sky, take away everything, and make everybody feel high" - Bob Marley

#18 Oberon_Command   Crossbones+   -  Reputation: 1862

Like
0Likes
Like

Posted 08 January 2013 - 07:06 PM

The point with all this is that the (key) properties of "references" exactly mirror those of pointers: they are datatypes held in variables, and they get copied by value when they are passed into functions, just as much as pointers. That's the functionality that C++ exposes and abstracts for us. C++ programmers might not think about it that way, since in the ideal case, they can be optimized just like any other code. But as we've agreed, that last is an implementation detail.
 

No, C++ programmers don't think about it that way because in terms of the semantics of C++ (not the implementation details), references are not values. We are discussing the semantics of C++ here. The implementation details are interesting and a C++ programmer will often find it useful to keep them in mind, but as far as I can tell, they are not relevant to the discussion of the semantics of C++, the programming language.

Edited by Oberon_Command, 08 January 2013 - 07:10 PM.


#19 SiCrane   Moderators   -  Reputation: 9561

Like
2Likes
Like

Posted 08 January 2013 - 08:24 PM

If you want to claim that implementation details are what counts, many C++ compilers don't have pass by value for objects. When you call a function that uses pass by value they create a new object in the caller's frame and pass by address to the function. In those compilers only primitives and pointers have pass by value. And then you have some compilers where some objects are pass by value and some others aren't, depending on size, whether or not they contain floating point variables or even more obscure criteria.

#20 iMalc   Crossbones+   -  Reputation: 2301

Like
0Likes
Like

Posted 08 January 2013 - 09:31 PM

Even pointers are a high-level language concept. At the level of implementation detail, there are no such things as pointers.
There are typically registers with values in them, and instructions that operate on those registers, some of which fetch values from places in memory relating to the value a register held.

Regardless of whatever merrit your argument has on some level, it simply isn't helpful to make the point you are trying to make, because it contradicts the description of the language itself.
"In order to understand recursion, you must first understand recursion."
My website dedicated to sorting algorithms




Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.



PARTNERS