fork(1) download
  1. #include <assert.h> // assert
  2. #include <string> // std::string
  3. using namespace std;
  4.  
  5. struct Person
  6. {
  7. string name;
  8.  
  9. void setValue( Person const& other )
  10. {
  11. name = other.name;
  12. }
  13.  
  14. void operator=( Person const& other ) { setValue( other ); }
  15.  
  16. Person( string const& _name )
  17. : name( _name )
  18. {}
  19. };
  20.  
  21. struct Student
  22. : Person
  23. {
  24. int studentId;
  25.  
  26. void setValue( Student const& other )
  27. {
  28. Person::setValue( other ); // Copies the name part.
  29. studentId = other.studentId; // Copies the id part.
  30. }
  31.  
  32. void operator=( Student const& other ) { setValue( other ); }
  33.  
  34. Student( string const& _name, int const _studentId )
  35. : Person( _name ), studentId( _studentId )
  36. {}
  37. };
  38.  
  39. int main()
  40. {
  41. Person a( "Hillary Clinton" );
  42. Student b( "John Smith", 12345 );
  43.  
  44. a = b; // Only the Person::operator= matches the arguments.
  45. // Here there is no `a.studentId`. The Student value has been SLICED.
  46. // The executed operator=() function copies only the name attribute.
  47.  
  48. assert( a.name == b.name );
  49. }
  50.  
Success #stdin #stdout 0.02s 2852KB
stdin
Standard input is empty
stdout
Standard output is empty