Remember:
- Replace Pass-by-value with Pass-by-reference-to-const as much as possible. The former is usually more efficient and avoids cutting problems (slicing problem).
- The above rules do not apply to built-in types, as well as STL iterators and function objects. For them, pass-by-value tend to be more appropriate.
classPerson { Public: Person (); Virtual~Person (); ...Private: stringname; stringaddress;};classStudent: PublicPerson { Public: Student (); ~Student (); ...Private: stringSchoolname; stringschooladdress; };BOOLvalidatestudent (Student s); Student Plato;BOOLPlatoisok =Validatestudent (Plato);//One-time student copy constructor//one-time person copy constructor//two string copy constructors in student//two string copy constructors in person//the corresponding six-second destructor uBOOLValidatestudent (Conststudent&s);//so there is no copy of the constructor and destructor calls.
classWindow { Public: ... stringName ()Const; Virtual voidDisplay ()Const;};classWindowwithscrollbars: PublicWindow { Public: ... Virtual voidDisplay ()Const;};voidPrintnameanddisplay (Window W)//Not right!{cout<<W.name (); W.display ();}//The parameter w is constructed as a Windows object, and the unique information for the Windowswithscrollbars object is lost. //so always call window::d isplay//SolutionsvoidPrintnameanddisplay (Constwindow&W) {cout<<W.name (); W.display ();}
Effective C + + clause 20: Prefer to replace pass-by-value with Pass-by-reference-to-const