can someone please let me konw what is the error in this code, not getting expected output.

#include<iostream>
using namespace std;

class myclass {
    public:
    int& num;
    myclass(int number) : num(number){}
};

int main(){
    int num1= 10000, num2 = 333;
    myclass mm(num1);
    myclass nn(num2);
    cout << mm.num << endl;
    cout << nn.num << endl;
    return 0;
}

number is a local variable whose lifetime ends when the constructor terminates. What do you suspect happens when the lifetime of the reference exceeds the lifetime of the referred?

Edited 3 Years Ago by deceptikon

can you please explain it? code works fine if i create single object.

int main(){
    int num1= 10000;
    myclass mm(num1);
    cout << mm.num << endl;
    return 0;
}

int& num;
This mean "num is another name for something - it's some other object completely, and this is just another name for that other object".

So what object is it another name for?
myclass(int number) : num(number){}
It's another name for this variable number, which exists for a very short time. It ceases to exist when the class constructor function finishes. So when you do this:
cout << mm.num << endl;
you're asking for the variable number which no longer exists, and what you'll actually get is whatever happens to be in the memory that the constructor function's temporary input parameter was put into.

Try this code; should illustrate things. It tells you the address of the class' variable num - the same place in memory, every time.

#include<iostream>
using namespace std;
class myclass {
    public:
    int& num;
    myclass(int number) : num(number){}
};
int main(){
    int num1= 10000, num2 = 333;
    myclass mm(num1);    cout << &(mm.num) << " " << mm.num <<endl;
    myclass nn(num2);    cout << &(nn.num) << " " <<nn.num << endl;
    cout << &(mm.num) << " " << mm.num <<endl;


    return 0;
}

Edited 3 Years Ago by Moschops

This article has been dead for over six months. Start a new discussion instead.