hello all

i want to know the uses of function returning by refrence and how to use them

i tried this but it gave an Error

int& sumz(int x,int y)
{
    int *sum = new int;
    *sum = x + y;
    return sum;
}
int& sumz(int x,int y)
{
    int *sum = new int;
    *sum = x + y;
    return *sum;
}

thanks .....:D:D

but i also want to know when to use it and what is it's uses

thanks .....:D:D

but i also want to know when to use it and what is it's uses

A function that returns a valid reference can be treated as a lvalue.

int& sumz(int x,int y)
{
    int *sum = new int;
    *sum = x + y;
    return *sum;
}
int x = 2, y = 3;

sumz(x, y) = 5; // valid because it is a reference

But your example is not a good place to use this since each time your method runs, you will declare a new location in memory that can hold an int and you can't retrieve that address unless you first store it.

#include <cstdlib>
#include <iostream>

using namespace std;

int& sumz(int x,int y)
{
    int *sum = new int;
    *sum = x + y;
    return *sum;
}

int main()
{
    
    int x = 2, y = 3, *z = NULL;
    
    z = &sumz(x, y); // 2 + 3 = 5, z points to new sum declared/defined in sumz(int, int) method
    
    (*z) += 5; // ( ((*sum) or (2 + 3) because z points to same address )    + 5 )
    
    cout << (*z) << endl; // printing the result

    delete z; // free the dynamic memory returned by the method (pointed to by z)
    
    cin.get();
    return 0;
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.