0

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;
}
3
Contributors
3
Replies
19
Views
4 Years
Discussion Span
Last Post by Moschops
1

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 by deceptikon

0
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;
}
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 by Moschops

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.