In C ++, variables are passed by reference for the following reasons:
**1) Modify local variables of the caller function: ** references (or Pointers) allow the called function to modify local variables of the caller function. For example, consider the following example program:
Output:
The new value of x is 20
**2) For passing large arguments: ** If the argument is large, passing by reference (or pointer) is more efficient because only the actual address is passed, not the whole object. For example, let’s consider the following Employee class and a function printEmpDetails () that prints the Employee details.
The problem with the above code is that each time printEmpDetails () is called, a new Employee object is constructed, which involves creating copies of all the data members. Therefore, a better implementation is to use Employee as a reference.
This is only true for structures and class variables, because we don’t have any efficiency advantage for basic types like int, char, etc.
3) Avoid object slicing: If we pass an object of a subclass to a function that needs a superclass object, then we slice the passed object if we pass it by value. For example, consider the following program, which prints “This is Pet Class.”
Output: This is Pet class
If passing by reference is used in the above program, it prints “This is Dog class” correctly. See the modified procedure below.
Output: This is Dog class
This is true for basic data types (e.g. Int, char,.. Etc.) is also invalid.
4) Implementing runtime polymorphism in functions We can make functions polymorphic by passing objects as references (or Pointers) to them.
For example, in the following program, print () receives a reference to a base class object. If a base object is passed, print () calls the base function show (); If a derived object is passed, the derived function show () is called.
Output:
In base
In derived
Every day to learn a little knowledge, I hope to help you ~
In addition, if you want to improve your programming ability, learn C language C++ programming! Pass on the curve, one step faster! The author here may be able to help you ~
C language C++ programming learning exchange circle, **QQ group [464501141] ** wechat public number: C language programming learning base
Share (source code, project actual combat video, project notes, basic introduction tutorial)
Welcome to change careers and learn programming partners, use more information to learn and grow faster than their own thinking oh!