FAQ 2.09 What are the basics of passing objects by reference?

graphics/new_icon.gif

Passing objects by reference is the most common way to pass objects to functions. C programmers often have a hard time adjusting to pass-by-reference, but it's generally worth the pain to make the transition.

 #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); } 

(1) Changes main()'s x object

(2) Note the const

(3) Error: Can't change an object via a const reference

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.



C++ FAQs
C Programming FAQs: Frequently Asked Questions
ISBN: 0201845199
EAN: 2147483647
Year: 2005
Pages: 566
Authors: Steve Summit

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net