0

Quick question, (C++)

Say I have a function called findPlayer( Player &p )

If I call that as follows

findPlayer(Player());

what is the const-ness of local p inside findPlayer?

In addition, is Player() passed by reference or value? I'm guessing value...

Volte
  • 1,905
  • 18
  • 25
  • 4
    `findPlayer(Player())` shouldn't even compile. – Mankarse May 18 '14 at 19:26
  • @Mankarse It shouldn't, but if I recall correctly, allowing temporaries for non-const references is one of the more prominent areas of non-conformance of one major C++ compiler. –  May 18 '14 at 19:30
  • 1
    @hvd: That may be true, but without mention of that, this question is fairly meaningless. – Mankarse May 18 '14 at 19:31
  • @Mankarse I'm only pointing it out because the OP may not realise it is invalid, because there is a fair chance the OP did try to compile it, and got no indication whatsoever that anything was wrong. –  May 18 '14 at 19:32
  • @Mankarse thanks for the feedback. I did compile and it hadn't complained specifically about that, however I'm in the process of overhauling a lot of code so it's not in a stable build at the moment. I will take this into consideration and see how it works moving forward. An interesting matter to note is that I've accomplished something similar with other objects throughout the code and it hasn't complained once. – Volte May 18 '14 at 19:52
  • 1
    @Volte: I'm assuming you are using MSVC, in which case I would suggest activating the [/Za](http://msdn.microsoft.com/en-us/library/0k0w269d.aspx) switch to disable the C++ incompatible extensions supplied by that compiler. – Mankarse May 18 '14 at 20:01

2 Answers2

0

Disregarding the fact that

findPlayer(Player());

shouldn't compile, the behavior of a p in findPlayer() is not dependent on how it gets called. That would defeat the purpose of the function's interface.

When you have a function whose interface is findPlayer(Player& p), you are telling the world that findPlayer can access anything from p that are available through the public interface of Player on on-const objects.

R Sahu
  • 204,454
  • 14
  • 159
  • 270
  • True, I guess what I mean't was what is the const-ness of a temporary object. (Didn't have the language to describe that until now) – Volte May 18 '14 at 19:54
  • @Volte Take a look at this [SO post on the subect](http://stackoverflow.com/questions/1565600/how-come-a-non-const-reference-cannot-bind-to-a-temporary-object). Hopefully things will make more sense after reading it. – R Sahu May 19 '14 at 00:40
0

findPlayer( Player &p ) with findPlayer(Player()) should give error indicating constant-ness, the function should be defined as findPlayer(const Player &p ) , and a constant reference will be useless except using a pass-by-reference approach for that method.

user3648895
  • 395
  • 10
  • 20