Search code examples
c++classoopfriend

c++ oop program doesn't give expected result


Consider the following piece of program:

class cls
{
   int vi;
public:
    cls(int v=37)
    {
        vi=v;
    } 
    friend int& f(cls);
};

int& f(cls c)
{
    return c.vi;
}

int main()
{
    const cls d(15);
    f(d)=8;
    cout<<f(d);
    return 0;
}

When I run it, the output is

15

but I don't understand why 15, because I thought it should've outputed 8, because of the

f(d)=8

function, which from what I understand makes the c.vi=8, but I might be wrong and the function probably does something else entirely, so then I ask, what is the purpose or what does the

friend int& f(cls);

function do?


Solution

  • Your program has Undefined Behavior - you are returning a dangling reference to local variable of a function (argument is a local variable as well).