Cpp pass by reference

C++ Pass By Reference Explained

In C++, you may need to allow a function to access one of its parameters directly without creating a copy. You may be passing a complex data structure as a parameter, or you could be looking to optimize the function’s performance on a very large number of function calls.

One way to achieve such access is to use “pass by reference.” In this guide, we’ll show you how to implement pass by reference and discuss when it makes the most sense to do so.

What Is Pass by Reference?

Pass by reference is something that C++ developers use to allow a function to modify a variable without having to create a copy of it. To pass a variable by reference, we have to declare function parameters as references and not normal variables.

#include using namespace std; void duplicate(int& b) < b*=2; >int main()

We’ll break this code down in a bit, but let’s first take a look at the differences between an argument and a parameter.

Arguments and Parameters

Although similar, arguments and parameters have different uses in code.

Читайте также:  Display message on button click in html

When you call upon a function, the values that get passed are known as arguments. The function sends the values of the arguments to the receiving function to take the place of parameters.

Parameters, on the other hand, are a formal way to show a placeholder for a variable in a function. They are used in the function itself and are assigned values based on arguments when the function is called.

Take a look at this example:

//More code Function CalcKilograms (Real Pounds) Declare Real Kilograms Assign Kilograms = (Pounds*2.2) Return Real Kilograms //More code

If the CalcKilograms function is called passing in the value 100, as in CalcKilograms(100), the argument is 100 and the parameter is Pounds.

How Does Pass By Reference Work With Functions?

Let’s take another look at our original example:

#include using namespace std; void duplicate(int& b) < b*=2; >int main()

If you recall, using pass by reference allows us to effectively “pass” the reference of a variable in the calling function to whatever is in the function being called. The called function gets the ability to modify the value of the argument by passing in its reference. This replaces the original argument before the parameters reference it.

In our program above, we have a pretty basic main function. This function first declares variable “x” to be 25 and then outputs that value. After that, we introduce a new function, duplicate, and then want to output the new value of “x.” This duplicate function is the key to using pass by reference to make changes to our argument “x.”

void duplicate(int& b) becomes our pass by reference. In our duplicate function, (int& b) creates variable “b” as a copy of “x,” referencing its value. The duplicate function performs the operator on “b,” and then replaces the value of “x” with the new value of “b.”

We get the following as a result:

This shows that the program returns the original value of “x” before the duplicate function, and then outputs the value of “x” after the pass by reference.

When Is Pass by Reference Most Useful?

Pass by reference serves key purposes in C++ code. Let’s take a look at when this technique is beneficial to use.

Modifying Local Variables of the Caller Function

As we saw above, we can use pass by reference to modify local variables of a function. When you call a function that needs to modify arguments, pass by reference is the only way to accomplish this task.

Passing Large-Sized Arguments

If an argument is significant in size (like a string that’s a list), it makes more sense to use pass by reference to avoid having to move the entire string. Effectively, pass by reference will pass just the address of the argument and not the argument itself. The example below is inefficient because a new number would create a copy of all data members.

// More code here class ClientNumber< private: string name; string number; // More code here >; void printNumber(ClientNumber num) < cout 

By transforming ClientNumber into a reference, we can prevent that from happening and make our program more efficient. From a coding standpoint, it’s as simple as adding in an ampersand:

// More code here class ClientNumber< private: string name; string number; // More code here >; void printNumber(ClientNumber& num) < cout 

Polymorphism in a Function

It’s possible to use pass by reference to make a function polymorphic by passing objects to it. In the example below, due to the reference in the core class, display() calls the core function show() if core is passed, and the alternate function show() if the alt object is passed.

#include using namespace std; class core < public: virtual void show() < cout >; class alt: public core < public: void show() < cout >; void display(core& c) < c.show(); >int main(void)

The program returns the following:

Alternatives to Pass By Reference

Within C++ there are two other options for passing arguments, each with their subtle differences.

Pass By Value

With pass by value, local parameters become copies of the original arguments that are passed in. Therefore, changes made in the function to the passed arguments do not affect the originals. Here’s a use of pass by value in comparison to our pass by reference example:

#include using namespace std; void duplicate(int b) < b*=2; >int main()

In both cases, the output for “x” is the same because changes to the arguments passed into the duplicate function do not affect the original arguments, which remain the same.

Pass By Pointer

Pass by pointer works even more similarly to pass by reference and even achieves the same result:

#include using namespace std; void duplicate(int* b) < *b*=2; >int main()

The key differences between pass by reference and pass by pointer lie in the fact that a pointer can store the address of any variable to a location in the memory. It’s also possible to not initialize a pointer and instead assign it to null.

Reference, on the other hand, always references a variable and shares a memory location with it. Changing the original variable also changes the reference variable. Also, it’s not possible to reassign a reference.

Learn C++ Online

Knowing how to use pass by reference with functions is integral to programming in C++.

Want to become a C++ developer? Check out our specialized C++ Nanodegree, where you’ll learn the language from industry experts by coding five projects of your own.

Источник

Passing object by reference in C++

Today, we will learn about passing objects to a function by reference method in C++. In C++ programming, many times we need to reflect the changes in actual parameters. So, here we need to pass an object by reference. If you want to learn how to do it, then you are in the right place. Here we will see sample programs. Here, in this tutorial, we will differentiate between pass by value and by reference. And in the end, you will realize the importance of pass by reference in C++ programming.

Reference variable in C++

A reference variable is an alias of another previously defined variable. Once you define a reference variable for an already existing variable, you can use both names. A variable name refers to a memory block in which data is stored. Defining a reference variable gives another name for the same memory block.

void main() < int a=5; int &b=a; coutreturn_type function_name(data_type &arg1,data_type &arg2,data_type &argn);

Thus in the pass by reference, an alias name is given to the actual parameters. The call by reference method is useful if you need to reflect on the changes done by a function. You can use a return statement if the function makes changes in exactly one parameter. But if multiple parameters are affected then call by reference will be useful.

C++ program for passing by reference

Now, we will see a program in C++ to illustrate passing objects by reference to a function. So, to illustrate this we will take a C++ class named Tourist.

#include using namespace std; class Tourist < int id; char name[30]; float amount; public: void get_input(void); friend void modify(Tourist&,float); void display(void); >; void Tourist::get_input() < cout>id; cout>name; cout>amount; > void Tourist::display() < coutvoid modify(Tourist &t,float new_amt) < t.amount=new_amt; coutint main() < float amt; Tourist t1; t1.get_input(); cout>amt; modify(t1,amt); cout

In the above program, we have created a class Tourist having variables id, name and amount paid by a tourist. Using the function get_input() we take the input about tourist information from the user. The display() function displays the details of a tourist. Other than these functions we have made modify() function as a friend of class Tourist.

A friend function cannot access variables of a class object directly. So, we need to pass the class object as a parameter to the function. This passing can be of two types –

Here, in this program, we have used pass by the reference method.

The output of the C++ program

The output of the above program is –

[email protected]:~/cpp$ g++ pass.cpp [email protected]:~/cpp$ ./a.out ENTER TOURIST ID : 11 ENTER NAME : siddharth ENTER AMOUNT PAID : 1900 --BEFORE MODIFICATION-- TOURIST ID : 11 TOURIST NAME : siddharth AMOUNT PAID : 1900 ENTER THE NEW AMOUNT : 2100 NEW AMOUNT FOR TOURIST 11 IS : 2100 --AFTER MODIFICATION-- TOURIST ID : 11 TOURIST NAME : siddharth AMOUNT PAID : 2100 [email protected]:~/cpp$

So, in the output, the amount before modification is 1900. Then we call the modify() function using call by the reference method. Because of this, the modification also reflects in the actual parameter. In the main() function, the amount paid after calling modify() function is 2100. So, the value of the object is changed by the modify() function due to pass by reference.

Importance of pass by reference method in C++

In pass by value method, we create a new object whose scope is limited to the function only. The changes are done with this temporary object. But the actual object remains the same. The modify() function prototype using call by value method will be –

void modify(Tourist t, float new_amt);

Here, whatever the changes are made it will be with local object ‘t’.

There is a great difference in output using call by value and call by reference –

Output in the call by value method –

[email protected]:~/cpp$ g++ pass1.cpp [email protected]:~/cpp$ ./a.out ENTER TOURIST ID : 11 ENTER NAME : siddharth ENTER AMOUNT PAID : 1900 --BEFORE MODIFICATION-- TOURIST ID : 11 TOURIST NAME : siddharth AMOUNT PAID : 1900 ENTER THE NEW AMOUNT : 2100 NEW AMOUNT FOR TOURIST 11 IS : 2100 --AFTER MODIFICATION-- TOURIST ID : 11 TOURIST NAME : siddharth AMOUNT PAID : 1900 [email protected]:~/cpp$

You can see that the amount after modification does not change. It is still 1900 and no change occurs.

Output in the call by reference method –

[email protected]:~/cpp$ g++ pass.cpp [email protected]:~/cpp$ ./a.out ENTER TOURIST ID : 11 ENTER NAME : siddharth ENTER AMOUNT PAID : 1900 --BEFORE MODIFICATION-- TOURIST ID : 11 TOURIST NAME : siddharth AMOUNT PAID : 1900 ENTER THE NEW AMOUNT : 2100 NEW AMOUNT FOR TOURIST 11 IS : 2100 --AFTER MODIFICATION-- TOURIST ID : 11 TOURIST NAME : siddharth AMOUNT PAID : 2100 [email protected]:~/cpp$

So, you can see the difference. In the call by reference method, the value of the amount changes. After modification, it is showing 2100. So the changes made in modify() function also reflects in the actual object.

Thanks a lot for reading this tutorial. I hope it helped you to clear the concept.

Источник

Оцените статью