I wrote the following code, and I was expecting to get
5
6
6
6, but I got 5 6 5 0 instead. It seems that “val” gets the reference correctly in the beginning, but then it gets lost. Does anybody know where is my mistake?
class Count {
public:
void add() {
val++;
}
void print() {
cout << val << endl;
}
Count(int c): val(c) {
}
private:
int &val;
};
int main() {
int c = 5;
Count teste(c);
teste.print();
teste.add();
teste.print();
cout << c << endl;
teste.print();
return 0;
}
Your constructor should take the parameter by reference, not by value.