c++classreferenceclass-variablesmember-variables

Memeber variable as class variable in C++ how does it happen?



I have a problem. I am currently working on a small example in c++ and can't figure out the explanation. Here is my problem:

#include <iostream>
using namespace std;

class X{
int& i ;  /* int i; */

public :
X(int k=100):i(k){ }



X(`const` X& x):i(x.i){}
void setI(int k){i=k;}
int getI(){cout <<"adresse: "<< &i << " Contenue: "<<i<<endl ; return i;}
};

int main(){
int i =7;

X a(i);
a.getI();

a.setI(5);

a.getI();

cout << "the value of i is: " << i << endl;

X b(a);
b.getI();
cout << "the value of i is: " << i << endl;

X c;
c.getI();
a.getI();

return 0;
}

So what I dont understand is why does the variable member i in the class X work like a class variable? I have searched online and found that it is called agregation and that it is used for some reasons but I can not understand why does it happen? How does the compiler do that?

Could you please explain this to me.
Thanks in Previous.


Solution

  • Your code has undefined behaviour, it doesn't have to work in any way at all.

    Here's the problem

    class X {
        int& i;
    public:
        X(int k = 100) : i(k) {}
        ...
    };
    

    k is a local variable, a parameter to the constructor. It no longer exists once the constructor has exitted.

    But your code takes a reference to that local variable. So your class ends up with a reference to an object wheich no longer exists. This is undefined behaviour.

    PS I'm not sure what you mean by class variable vs. member variable. To me those terms mean the same thing. But whatever strange behaviour you are seeing, it's explained by the undefined behaviour that your program has, as described above.

    PPS I see class variable means static member variable, makes sense, so ignore the previous paragraph.