fork(3) 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. bool isEqualTo( Person const& other ) const
  10. {
  11. return (name == other.name);
  12. }
  13.  
  14. Person( string const& _name )
  15. : name( _name )
  16. {}
  17. };
  18.  
  19. bool operator==( Person const& a, Person const& b )
  20. { return a.Person::isEqualTo( b ); }
  21.  
  22. struct Student
  23. : Person
  24. {
  25. int studentId;
  26.  
  27. bool isEqualTo( Student const& other ) const
  28. {
  29. return (Person::isEqualTo( other ) && studentId == other.studentId);
  30. }
  31.  
  32. Student( string const& _name, int const _studentId )
  33. : Person( _name ), studentId( _studentId )
  34. {}
  35. };
  36.  
  37. bool operator==( Student const& a, Student const& b )
  38. { return a.Student::isEqualTo( b ); }
  39.  
  40. int main()
  41. {
  42. Person a( "Hillary Clinton" );
  43. Student b( "John Smith", 12345 );
  44.  
  45. a = b; // I once expected this assignment to NOT COMPILE!
  46. // Here there is no `a.studentId`. The Student value has been SLICED.
  47.  
  48. assert( a == b ); // The Person class' isEqualTo still says "equal".
  49. }
  50.  
Success #stdin #stdout 0.02s 2852KB
stdin
Standard input is empty
stdout
Standard output is empty