fork download
  1. #include <iostream>
  2.  
  3. struct base
  4. {
  5. virtual void print_type() const {
  6. std::cout << "base\n";
  7. }
  8. };
  9.  
  10. struct derived : public base
  11. {
  12. void print_type() const {
  13. std::cout << "derived\n";
  14. }
  15. };
  16.  
  17. int main()
  18. {
  19. base b; // b is an object of type base. It can never be anything else.
  20. b.print_type();
  21.  
  22. derived d;
  23. d.print_type();
  24.  
  25. b = d; // If we set b equal to an object of type derived, it is still an object of type base.
  26. b.print_type();
  27.  
  28. base* ptr = &b; // ptr is a pointer to some class in the base hierarchy
  29. ptr->print_type(); // if we point it a a base class object, we get base class behavior
  30.  
  31. ptr = &d; // if we point it a derived class object, we get derived class behavior
  32. ptr->print_type();
  33. }
Success #stdin #stdout 0s 3296KB
stdin
Standard input is empty
stdout
base
derived
base
base
derived