#include "Car.hpp" void f(Car& a) { a.startEngine(); <-- 1 // ... } void g(const Car& b) <-- 2 { b.startEngine(); <-- 3 // ... } main() { Car x; f(x); g(x); }
Function f() illustrates pass-by-reference (the & between the type name and the parameter name indicates pass-by-reference). In this case, a is main()'s x object not a copy of x nor a pointer to x, but another name for x itself. Therefore anything done to a is really done to x; for example a.startEngine() actually invokes x.startEngine(). Function g() illustrates pass-by-reference-to-const. Parameter b is the caller's object, just as before, but b has an additional restriction: it can only inspect the object, not mutate the object. This means g() has a look-but-no-touch agreement with its callers g() guarantees to its callers that the object they pass will not be modified. For example, if a programmer erroneously called b.startEngine(), the compiler would detect the error and would issue a diagnostic at compile time (assuming startEngine() is not a const member function; see FAQ 2.17). Reference-to-const is similar in spirit to pass-by-value (see FAQ 2.10), but is implemented much more efficiently. |