![]() |
In C++, we can pass arguments to a function as a value, reference (or pointer). Each method has its unique benefits and uses. In this article, we will discuss the application or cases where we should pass the arguments by reference or a pointer. But first, let’s quickly revisit the definitions of pointers and references. Pointers in C++Pointers are symbolic representations of addresses. They are the variables that store the memory address of the data. The address of the variable you’re working with is assigned to the pointer variable that points to the same data type (such as an int or string). We can use the pointers to pass arguments address to the function i.e. pass by pointer method. Syntax to Declare Pointerdata_type * pointer_name = &some_variable; To learn more about pointers, visit the article – C++ Pointers References in C++When a variable is declared as a reference, it becomes an alternative name for an existing variable. A variable can be declared as a reference by putting ‘&’ in the declaration. They are similar to pointers in the way that ‘&’ is used for signifying the address of a variable or any memory. The difference is that we don’t need to use *(dereference operator) to access the value of the reference. We can use the reference name to directly access the value. Syntax to Declare Referencesdata_type &ref = variable; To learn more about pointers, visit the article –C++ References When to Pass Arguments by Reference or Pointer in C++?In C++, arguments are passed by reference or pointer in the following cases: 1. To Modify the Local Variable of the Caller FunctionA reference (or pointer) allows a called function to modify the local variables of the caller function that are passed as the arguments. This means that a function can modify a variable in the calling function by using a pointer to that variable. Example C++
Output
Old value of a is 2 New value of a is 4 2. Avoiding Copy of Large DataImagine a function that has to receive a large-sized object, if we pass it without reference, a new copy of it is created which causes a waste of CPU time and memory. We can use references or pointers to avoid this. Example C++
Output
Name: Abhishek Company: GeekforGeeks 3. To Achieve Run Time Polymorphism in a FunctionWe can make a function polymorphic by passing objects as references (or pointers) to it instead of the actual objects. It allows us to achieve runtime polymorphism in our program. Example: C++
Output
In base In derived 4. To Return Multiple ValuesWhen we want to return multiple values from a function, passing pointers as function parameters allows us to modify the values of variables passed to the function. Example: C++
Output
Sum is: 6 Difference is: 2 |
Reffered: https://www.geeksforgeeks.org
C++ |
Related |
---|
![]() |
![]() |
![]() |
![]() |
![]() |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 12 |