How can I pass a pointer (Object *ob
) to a function which prototype is void foo(Object &)
?
-
The title says "cast [sic] reference to pointer" but the question starts with a pointer and needs a reference. Which direction is it?– MSaltersApr 16, 2012 at 10:56
-
@MSalters it should be convert. I'm editing it. But I was looking for whatever solution I get, so I mentioned cast– DewsworldApr 16, 2012 at 11:00
Add a comment
|
2 Answers
Call it like this:
foo(*ob);
Note that there is no casting going on here, as suggested in your question title. All we have done is de-referenced the pointer to the object which we then pass to the function.
-
31@Ricobob That's what happens on SO so very often. Answers to simple questions that can be easily understood often garner lots of up votes. Long and complex answers to tricky questions often get few upvotes because voters can't easily judge merit. As for rep, I got nothing on this because of rep cap. ;-) But I heartily agree. I wish complex answers garnered more rep. Apr 16, 2012 at 21:42
-
6Does this create a copy of
ob
, or just convert (if not cast) the pointer to a reference? What ifob
wasnullptr
? Jun 15, 2014 at 23:15 -
7@Drew It simply dereferences the pointer. No copy. No conversion. No cast. The object is then passed by reference to the function. It is an error if the point is null. Jun 16, 2014 at 6:33
-
1
-
2Just a note : if you want to have the reference without passing to function use it like this :
Object& objref = *ob;
– user13119880Oct 6, 2020 at 21:36
foo(*ob);
You don't need to cast it because it's the same Object type, you just need to dereference it.
-
guessing amd adding lots of ... is not usually the format of a good answer here (even though it is correct in this case), that's probably why you got one downvote. Apr 16, 2012 at 11:20
-
7bhhaaa, I added the "I guess" because it made me write at least 30 chars. that's also way I add the "..........." Apr 16, 2012 at 11:41
-
13@RoeeGavirel I'm your first up-voter because I felt the downvote to be harsh. FWIW you can get over the 30 char limit but adding an HTML comment <!-----------------------------> which I did in my first version ofthe answer! My edit to your answer shows how. Apr 16, 2012 at 12:04
-
-
2@KeithM - That's a random comment and -1. The answer was given about 6 years ago, also the question didn't ask for the "why" it only asked for the "how". But sure, I'll add an explanation. Dec 5, 2018 at 7:09