I've been programming in C++ for a while but certainly wouldn't call myself an expert. This question isn't being asked to solve a practical problem that I have, it's more about understanding what C++ is doing.
Imagine I have a function that expects a single paramater:
void doSomething(SomeClass& ref)
{
// do something interesting
}
(Note: the parameter is a reference to SomeClass) Then I call the function like this:
int main(int argc, char *argv[])
{
SomeClass a;
doSomething(a);
}
Why is this legal C++? The function is expecting a reference to SomeClass, but I'm passing it a statically allocated variable of type SomeClass. A reference is like a pointer no? If we were to replace the reference with a pointer the compiler complains. Why is the reference different to a pointer in this way, what's going on behind the scenes?
Sorry if this is a stupid question, it's just been buggin me!
You're not passing it "a statically allocated variable of type SomeClass", you're passing it a reference to a
SomeClassobject you created on the stack inmain().Your function
Causes a reference to
ain main to be passed in. That's what&after the type in the parameter list does.If you left out the
&, thenSomeClass's (a's) copy constructor would be called, and your function would get a new, local copy of theaobject inmain(); in that case anything you did torefin the function wouldn't be seen back inmain()