Passing objects to functions
1. Use object as function parameter
Objects can be passed to functions as parameters in the same way as other types of data.
When an object is passed to a function, it is passed to the function through a pass value call.
Therefore, any modification of an object in a function does not affect the object itself that calls the function.
Example 3.11 uses an object as a function parameter.
#include<iostream.h> class aClass{ public: aClass(int n) { i=n; } void set(int n){ i=n; } int get( ){ return i; } private: int i; }; void sqr(aClass ob) { ob.set(ob.get()*ob.get()); cout<<"copy of obj has i value of "; cout<<ob.get()<<"\n"; } main() { aClass obj(10); sqr(obj); cout<<"But, obj.i is unchanged in main:"; cout<<obj.get( ); return 0; }
copy of obj bas i value of 100 But, obj.i is unchanged in mainā¶10
2. Use object pointer as function parameter
The object pointer can be used as the parameter of the function, and the object pointer can be used as the parameter of the function to realize the address call, which can change the value of the parameter object in the called function, and realize the information transfer between functions.
At the same time, using the object pointer argument can only transfer the address value of the object to the parameter without copying the copy, which can improve the running efficiency and reduce the time and space cost.
When the parameter of a function is an object pointer, the corresponding argument of the calling function should be the address value of an object.
Example 3.12 using an object pointer as a function parameter
#include<iostream.h> class aClass { public: aClass(int n) { i=n; } void set(int n){ i=n; } int get(){ return i;} private: int i; }; void sqr(aClass *ob) { ob->set(ob->get() * ob->get()); cout<<"Copy of obj has i value of "; cout<<ob->get()<<"\n"; } main() { aClass obj(10); sqr(&obj); cout<<"Now, obj.i in main() has been changed :"; cout<<obj.get() <<"\n"; return 0; }
3. Use object reference as function parameter
Using object reference as function parameter not only has the advantage of using object pointer as function parameter, but also is simpler and more direct.
Example 3.13 using an object reference as a function parameter
#include<iostream.h> class aClass { public: aClass(int n) { i=n; } void set(int n) { i=n; } int get() { return i;} private: int i; }; void sqr(aClass& ob) { ob.set(ob.get() * ob.get()); cout<<"Copy of obj has i value of "; cout<<ob.get()<<"\n"; } main() { aClass obj(10); sqr(obj); cout<<"Now, obj.i in main() has been changed :"; cout<<obj.get() <<"\n"; return 0; }