Object-Oriented Thinking in C++: Passing Objects to Functions

Objects can be passed to a function by value or by reference, but it is more efficient to pass objects by reference.       

So far, you have learned how to pass arguments of primitive types, array types, and string types to functions. You can pass any types of objects to functions. You can pass objects by value or by reference. Listing 10.3 gives an example that passes an object by value.

LisTing 10.3 PassObjectByValue.cpp

1 #include <iostream>
2
// CircleWithPrivateDataFields.h is defined in Listing 9.9
3 #include “CircleWithPrivateDataFields.h”
4 using namespace std;
5
6
void printCircle(Circle c)
7 {
8    cout <<
“The area of the circle of ”
9    << c.getRadius() << ” is ” << c.getArea() << endl;
10 }
11
12
int main()
13 {
14    Circle myCircle(
5.0);
15    printCircle(myCircle);
16
17   
return 0;
18 }

The Circle class defined CircleWithPrivateDataFields.h from Listing 9.9 is included in line 3. The parameter for the printCircle function is defined as Circle (line 6). The main function creates a Circle object myCircle (line 14) and passes it to the printCircle function by value (line 15). To pass an object argument by value is to copy the object to the function parameter. So the object c in the printCircle function is independent of the object myCircle in the main function, as shown in Figure 10.9a.

Listing 10.4 gives an example that passes an object by reference.

Listing 10.4 PassObjectByReference.cpp

1 #include <iostream>
2
#include “CircleWithPrivateDataFields.h”
3 using namespace std;
4
5
void printCircle(Circle& c)
6 {
7    cout <<
“The area of the circle of ”
8    << c.getRadius() << ” is ” << c.getArea() << endl;
9 }
10
11
int main()
12 {
13    Circle myCircle(
5.0);

14    printCircle(myCircle);
15
16   
return 0;
17 }

A reference parameter of the Circle type is declared in the printCircle func­tion (line 5). The main function creates a Circle object myCircle (line 13) and passes the reference of the object to the printCircle function (line 14). So the object c in the printCircle function is essentially an alias of the object myCircle in the main function, as shown in Figure 10.9b.

Though you can pass an object to a function by value or by reference, passing by reference pass object by reference is preferred, because it takes time and additional memory space to pass by value.

Source: Liang Y. Daniel (2013), Introduction to programming with C++, Pearson; 3rd edition.

Leave a Reply

Your email address will not be published. Required fields are marked *