Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Behaviour of pass by reference and its scope

Tags:

c++

c++11

In the below code the variable a is passed to a constructor by reference, received by the parameter x. Then x is passed as a reference to an attribute. The attribute is then initialized with value 3. The program outputs the value 3 when running.

MY QUESTION

Shouldn't the program crash or show 2 because after the constructor is called x should go out of scope and be released and its address should be freed right. and trying to write to it should give a memory access violation. However in this case the x is still in program control holding the address of 'a'

Is this valid c++ behavior or am i missing something?

#include <iostream>
#include <conio.h>

using namespace std;

class myclass {

public:
    int& attribute;
    myclass(int& x):attribute(x) {

    }

    void func() {
        attribute = 3;
    }
};

int main() {
    int a = 2;
    myclass obj(a);
    obj.func();
    std::cout << a;
    _getch();
}
like image 265
Anu Panicker Avatar asked Jan 26 '23 22:01

Anu Panicker


1 Answers

No this program is fine. attribute is a reference to a. The fact that x has gone out of scope is neither here nor there.

If you changed your code to

myclass(int x):attribute(x)

then that would be a problem.

like image 81
john Avatar answered Jan 31 '23 22:01

john