×

C++ Tutorial

C++ Data types

C++ Operators & Keywords

C++ Conditional Statements

C++ Functions

C++ 'this' Pointer, References

C++ Class & Objects

C++ Constructors & Destructors

C++ Operator overloading

C++ 11 (Advance C++)

C++ Preparation

C++ Header Files & Functionsr

Data Structure with C++

C++ - Miscellaneous

C++ Programs

Function returning reference in C++

C++ - Function returning reference: Here, we will learn with a C++ program, how to return a reference from function?

What is Function Returning Reference in C++?

As we know that we can take only variable on the left side in C++ statements, we can also use a function on the left side, if a function is returning a reference to the variable. The variable whose reference is being returned may only be:

  1. Global variable
  2. Static variable

Using this type of function, we can assign variable. We can understand this situation with the help of the program.

Example

Consider the program:

using namespace std;
#include <iostream>

int X; //Global variable

//prototype of funToSetX()
int & funToSetX();

int main()
{
    X = 100;
    
    int Y;
    
    Y = funToSetX();
    cout<<"1.Value of X is : "<< Y<<endl;
    
    funToSetX() = 200;
    
    Y = funToSetX();
    cout<<"2.Value of X is : "<< Y<<endl;
        
    return 0;    
}

//Definition of funToSetX()
int & funToSetX()
{
    return X;    
}

Output

1.Value of X is : 100
2.Value of X is : 200

In this program, we are using X as a global variable and using function funToSetX(), we are returning a reference to global variable X. We assign 100 to X in starting of main() function, then get value of from funToSetX() to Y. So, here we are using funToSetX() function on left and right both side in C++ statement. Normally we cannot do this with normal functions in C++.

Related Tutorials

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.