Default Assignment Operator and References

 

  We have discussed assignment operator overloading for dynamically allocated resources here . This is a an extension of the previous post. In the previous post, we discussed that when we don’t write our own assignment operator, compiler created assignment operator does shallow copy and that cause problems.

  What happens when we have references in our class and there is no user defined assignment operator.

  For example, predict the output of following program.

 1 #include<iostream>
 2 using namespace std;
 3 
 4 class Test
 5 {
 6     int x;
 7     int &ref;
 8 public:
 9     Test (int i):x(i), ref(x) 
10     {
11     }
12     void print() 
13     { 
14         cout << ref; 
15     }
16     void setX(int i) 
17     { 
18         x = i; 
19     }    
20 };
21 
22 int main()
23 {
24     Test t1(10);
25     Test t2(20);
26     t2 = t1;
27     t1.setX(40);
28     t2.print();
29     return 0;
30 }

  Output:

  Compiler Error: non-static reference member 'int& Test::ref', can't use default assignment operator

  Compiler doesn’t creates default assignment operator in following cases:

  1. Class has a nonstatic data member of a const type or a reference type
  2. Class has a nonstatic data member of a type which has an inaccessible copy assignment operator
  3. Class is derived from a base class with an inaccessible copy assignment operator

  When any of the above conditions is true, user must define assignment operator.

  For example, if we add an assignment operator to the above code, the code works fine without any error.

 1 #include<iostream>
 2 using namespace std;
 3 
 4 class Test
 5 {
 6     int x;
 7     int &ref;
 8 public:
 9     Test (int i):x(i), ref(x) 
10     {
11     }
12     void print() 
13     { 
14         cout << ref; 
15     }
16     void setX(int i) 
17     { 
18         x = i; 
19     }    
20     Test &operator = (const Test &t) 
21     { 
22         x = t.x; 
23         return *this; 
24     } 
25 };
26 
27 int main()
28 {
29     Test t1(10);
30     Test t2(20);
31     t2 = t1;
32     t1.setX(40);
33     t2.print();
34     return 0;
35 }

  Output:  10

 

 

 

  Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

  转载请注明:http://www.cnblogs.com/iloveyouforever/

  2013-11-26   22:01:46

转载于:https://www.cnblogs.com/iloveyouforever/p/3444396.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值