fork(1) download
  1. #include <iostream>
  2. using namespace std;
  3.  
  4. // Shape is abstract class: some methods are already available, some are not
  5. class Shape
  6. {
  7. public:
  8. // This is already implemented and ready for polymorphism
  9. virtual void area() { cout<<"Shape area"<<endl;}
  10. // You MUST implement this
  11. virtual void implement_me() = 0;
  12. };
  13.  
  14. class Circle : public Shape
  15. {
  16. public:
  17. virtual void area() { cout<<"Circle area"<<endl;}
  18. void implement_me() { cout<<"I implemented it just because I had to"<<endl;}
  19. };
  20.  
  21. class HalfCircle : public Circle
  22. {
  23. public:
  24. virtual void area() { cout<<"HalfCircle area"<<endl;}
  25. };
  26.  
  27.  
  28. // ShapeInterface is a pure class or interface: everything must be implemented!
  29. class ShapeInterface
  30. {
  31. public:
  32. virtual void area() = 0;
  33. };
  34.  
  35. class CircleFromInterface : public ShapeInterface
  36. {
  37. public:
  38. // You MUST implement this!
  39. virtual void area() { cout<<"CircleFromInterface area from interface"<<endl;};
  40. };
  41.  
  42.  
  43.  
  44. int main() {
  45.  
  46. Shape* ptr_to_base = new HalfCircle();
  47. ptr_to_base->area(); // HalfCircle area, polymorphism
  48. ptr_to_base->Shape::area(); // Shape area
  49. ptr_to_base->implement_me(); // from Circle
  50.  
  51.  
  52. ShapeInterface *ptr_to_base_int = new CircleFromInterface();
  53. ptr_to_base_int->area(); // Just the derived has it
  54.  
  55. return 0;
  56.  
  57.  
  58. }
Success #stdin #stdout 0s 3472KB
stdin
Standard input is empty
stdout
HalfCircle area
Shape area
I implemented it just because I had to
CircleFromInterface area from interface