FAQ 2.10 What are the basics of passing objects by value?

graphics/new_icon.gif

Beware: passing objects by value can be dangerous in some situations. Often it is better to pass objects by reference-to-const (FAQ 2.09) than to pass them by value. For example, pass-by-value won't work if the destination type is an abstract base class (see FAQ 2.24) and can result in erroneous behavior at runtime if the parameter's class has derived classes (see FAQ 24.12, 28.04). However if the class of the parameter is guaranteed not to have derived classes, and if the function being called needs a local copy to work with, pass-by-value can be useful.

 #include "Car.hpp" void f(Car a) {   a.startEngine();                                   <-- 1 } int main() {   Car x;   f(x); } 

(1) Changes a local copy of the original object

Since f()'s a is a copy of main()'s x, any changes to a are not reflected in x.



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