-3

It sesms in C++ it's alright to re-assign a reference, bounding it to another object. However, the code below cannot compile:

ostream &os_ref = cerr;
os_ref = cout;

Can anybody tell me what's wrong? Error information is listed below.

temp.cpp: In function ‘int main()’:
temp.cpp:15:12: error: use of deleted function ‘std::basic_ostream<char>& std::basic_ostream<char>::operator=(const std::basic_ostream<char>&)’
     os_ref = cout;
            ^
In file included from /usr/include/c++/4.9/iostream:39:0,
                 from temp.cpp:1:
/usr/include/c++/4.9/ostream:58:11: note: ‘std::basic_ostream<char>& std::basic_ostream<char>::operator=(const std::basic_ostream<char>&)’ is implicitly deleted because the default definition would be ill-formed:
     class basic_ostream : virtual public basic_ios<_CharT, _Traits>
           ^
/usr/include/c++/4.9/ostream:58:11: error: use of deleted function ‘std::basic_ios<char>& std::basic_ios<char>::operator=(const std::basic_ios<char>&)’
In file included from /usr/include/c++/4.9/ios:44:0,
                 from /usr/include/c++/4.9/ostream:38,
                 from /usr/include/c++/4.9/iostream:39,
                 from temp.cpp:1:
/usr/include/c++/4.9/bits/basic_ios.h:66:11: note: ‘std::basic_ios<char>& std::basic_ios<char>::operator=(const std::basic_ios<char>&)’ is implicitly deleted because the default definition would be ill-formed:
     class basic_ios : public ios_base
           ^
In file included from /usr/include/c++/4.9/ios:42:0,
                 from /usr/include/c++/4.9/ostream:38,
                 from /usr/include/c++/4.9/iostream:39,
                 from temp.cpp:1:
/usr/include/c++/4.9/bits/ios_base.h:789:5: error: ‘std::ios_base& std::ios_base::operator=(const std::ios_base&)’ is private
     operator=(const ios_base&);
     ^
In file included from /usr/include/c++/4.9/ios:44:0,
                 from /usr/include/c++/4.9/ostream:38,
                 from /usr/include/c++/4.9/iostream:39,
                 from temp.cpp:1:
/usr/include/c++/4.9/bits/basic_ios.h:66:11: error: within this context
     class basic_ios : public ios_base
           ^
Warbean
  • 547
  • 2
  • 5
  • 19

2 Answers2

3

References are bound to an object, you can never reassign it.

Reference remain as an alias to which it was initialized at time of creation.

P0W
  • 46,614
  • 9
  • 72
  • 119
3

In C++ it's alright to re-assign a reference, bounding it to another object.

No, it isn't

Can anybody tell me what's wrong?

In C++, you cannot re-assign a reference to bind it to another object. A reference is an alias to another object. If you "assign" a reference, you are assigning to the referred object, not changing the object the reference refers to.

For example:

flag

int a = 3, b = 4;
int &ref = a;
ref = b;                     // like saying a = b;
std::cout << a << std::endl; // prints 4
juanchopanza
  • 223,364
  • 34
  • 402
  • 480