returning reference from member function
Jan 23, 2013 at 4:16am UTC
Hello, I am new registered user to this forum although i have browsed before. I already read one related thread from
assassinbeast but that did not answer my question. So here is my question. Why doesn't dbl_b in my code on lines 19,20 below return 16 instead of 4? dbl_c works as expected. Thanks!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
class data1
{
int i;
public :
data1() {i=1;}
void seti(int ii) {i=ii;}
void geti() {cout << i << endl;}
void dbl_a(){i=i*2;}
data1 dbl_b() {i=i*2;return *this ;}
data1& dbl_c() {i=i*2;return *this ;}
};
int main()
{
data1 d1,d2;
d1.geti(); //outputs 1
d1.dbl_a();
d1.geti(); //outputs 2
d1.dbl_b().dbl_b().dbl_b();
d1.geti(); //outputs 4 not 16. Why is that?
d1.dbl_c().dbl_c().dbl_c();
d1.geti(); //outputs 32 as expected
}
Jan 23, 2013 at 4:35am UTC
dbl_b() returns a copy of *this.
So, line 19 is equivalent to:
1 2 3
temp = d1.dbl_b() ;
temp2 = temp.dbl_b() ;
temp2.dbl_b() ;
You'll notice the method is only called once on d1, thus the output.
Jan 23, 2013 at 5:09am UTC
That explains it perfectly. Thank you very much. So dbl_b gets called only once on d1.
The key is, as you said, dbl_b returns a copy of
*this
not the original
*this
(d1)
Based on what you said I modified the code a bit and now I get 16 on line 19.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
class data1
{
int i;
public :
data1() {i=1;}
void seti(int ii) {i=ii;}
void geti() {cout << i << endl;}
void dbl_a(){i=i*2;}
data1 dbl_b() {i=i*2;return *this ;}
data1& dbl_c() {i=i*2;return *this ;}
};
int main()
{
data1 d1,d2;
d1.geti(); //outputs 1
d1.dbl_a();
d1.geti(); //outputs 2
(d1.dbl_b().dbl_b().dbl_b()).geti(); //now this shows 16
d1.geti(); //outputs 4 since dbl_b is called only once on d1
d1.dbl_c().dbl_c().dbl_c();
d1.geti(); //outputs 32 as expected
}
Last edited on Jan 23, 2013 at 5:14am UTC
Topic archived. No new replies allowed.