fork(1) download
  1. // Remove "x" to invoke feature.
  2. #define xTEST_BAD_ASSIGN
  3.  
  4. #if defined( CPP11 )
  5. # define OVERRIDE override
  6. # define NOEXCEPT noexcept
  7. #else
  8. # define OVERRIDE
  9. # define NOEXCEPT throw()
  10. #endif
  11.  
  12. //---------------------------------------------------------------------------
  13. #include <assert.h> // assert
  14. #include <algorithm> // std::swap
  15. #include <exception> // std::terminate
  16. #include <string> // std::string
  17. #include <iostream> // std::wcout, std::wcerr, std::endl
  18. using namespace std;
  19.  
  20. #define FATAL_ERROR( s ) \
  21.   assert( !s ); wcerr << s << endl; terminate();
  22.  
  23. class Person
  24. {
  25. private:
  26. string name_;
  27.  
  28. public:
  29. string name() const { return name_; }
  30.  
  31. virtual void swapWith( Person& other ) NOEXCEPT
  32. {
  33. using std::swap; swap( name_, other.name_ );
  34. }
  35.  
  36. void operator=( Person other ) { swapWith( other ); }
  37.  
  38. Person( string const& name )
  39. : name_( name )
  40. {}
  41. };
  42.  
  43. class Student
  44. : public Person
  45. {
  46. private:
  47. int studentId_;
  48.  
  49. virtual void swapWith( Person& ) NOEXCEPT OVERRIDE
  50. {
  51. FATAL_ERROR( "Student::swapWith( Person& ): dest. value slicing" );
  52. }
  53.  
  54. public:
  55. int studentId() const { return studentId_; }
  56.  
  57. virtual void swapWith( Student& other ) NOEXCEPT
  58. {
  59. Person::swapWith( other );
  60. using std::swap; swap( studentId_, other.studentId_ );
  61. }
  62.  
  63. void operator=( Student other ) { swapWith( other ); }
  64.  
  65. Student( string const& name, int const studentId )
  66. : Person( name ), studentId_( studentId )
  67. {}
  68. };
  69.  
  70. wostream& operator<<( wostream& stream, string const& s )
  71. {
  72. return (stream << s.c_str());
  73. }
  74.  
  75. int main()
  76. {
  77. Person a( "Hillary Clinton" );
  78. Student b1( "John Smith", 12345 );
  79. Student b2( "Mary Jones", 88888 );
  80. Person& bAsPerson = b1; // OK.
  81.  
  82. wcout
  83. << "Name: " << b1.name()
  84. << ". Student id: " << b1.studentId() << "."
  85. << endl;
  86.  
  87. #ifdef TEST_BAD_ASSIGN
  88. bAsPerson = a; // Terminates at run-time (i.e. crash).
  89. #else
  90. b1 = b2; // Good/allowed assignment.
  91. #endif
  92.  
  93. wcout
  94. << "Name: " << b1.name()
  95. << ". Student id: " << b1.studentId() << "."
  96. << endl;
  97. }
  98.  
Success #stdin #stdout 0.01s 2876KB
stdin
Standard input is empty
stdout
Name: John Smith. Student id: 12345.
Name: Mary Jones. Student id: 88888.