vendredi 15 juin 2018

Reference return value and value updation in destructor

#include <iostream>
using namespace std;

int i; //1 - global

class Test
{
public:
    ~Test()
    {
        i = 10;
    }
};

int& foo()
{
    i = 3; //2 - local
    Test ob;
    return i;
}

int main()
{
    cout << "i = " << foo() << endl; // output: i = 10
    return 0;
}

I have queries for above code: 1. Variable i being local to foo, reference of which cannot be used (automatic variable). How does above code execute? 2. The Test object in foo function will be destroyed after return statement. How does foo function returns reference of 1 with updated value?

Aucun commentaire:

Enregistrer un commentaire