fork download
  1. #include <iostream>
  2. #include <vector>
  3. using namespace std;
  4.  
  5. class Shape {
  6. protected:
  7. Shape() {} // Having a protected constructor only allows you to
  8. // call it from the same or derived class
  9. public:
  10. virtual void func()=0;
  11. };
  12.  
  13. class Circle : public Shape {
  14. public:
  15. Circle() { }
  16. void func() { cout << "Hello from a Circle object" << endl; }
  17. };
  18.  
  19. class Square : public Shape {
  20. public:
  21. Square() { }
  22. void func() { cout << "Hello from a Square object" << endl; }
  23. };
  24.  
  25. int main() {
  26.  
  27. std::vector<Shape*> shapes;
  28. Circle c;
  29. Square s;
  30. shapes.push_back(&c); // Store the address of the object
  31. shapes.push_back(&s); // Store the address of the object
  32.  
  33. // A call through a pointer to a virtul polymorphic class
  34. // will make sure to call the appropriate function
  35. Shape ea;
  36. shapes[0]->func(); // Hello from a circle object
  37. shapes[1]->func(); // Hello from a square object
  38.  
  39.  
  40. }
Compilation error #stdin compilation error #stdout 0s 3428KB
stdin
Standard input is empty
compilation info
prog.cpp: In function ‘int main()’:
prog.cpp:7:9: error: ‘Shape::Shape()’ is protected
         Shape() {} // Having a protected constructor only allows you to
         ^
prog.cpp:35:11: error: within this context
     Shape ea;
           ^
prog.cpp:35:11: error: cannot declare variable ‘ea’ to be of abstract type ‘Shape’
prog.cpp:5:7: note:   because the following virtual functions are pure within ‘Shape’:
 class Shape {
       ^
prog.cpp:10:22: note: 	virtual void Shape::func()
         virtual void func()=0;
                      ^
stdout
Standard output is empty