0
#include<iostream> 
using namespace std; 

class Test     
{ 
    int x; 
    int &ref; 
public: 
    Test (int i):x(i), ref(x) {} 
    void print() { cout << ref; } 
    void setX(int i) { x = i; }     
}; 

int main()     
{     
    Test t1(10);     
    Test t2(20);     
    t2 = t1;     
    t1.setX(40);     
    t2.print();     
    return 0;     
} 

This program gives an compiler error

Pete Becker
  • 74,985
  • 8
  • 76
  • 165

1 Answers1

0

References and const variables can only be given a value at construction time. The assignment operator only works on objects that are already constructed.

Mark Ransom
  • 299,747
  • 42
  • 398
  • 622
  • Here object will construct before only then how it would give error? – user12238659 Oct 18 '19 at 16:51
  • @user12238659 once the object is constructed, those references and const values can't be changed. The default assignment operator requires the values of all members to be copied, i.e. changed. – Mark Ransom Oct 18 '19 at 17:32