Advertisement
ivanwidyan

Inheritance and Polymorphism for Drawing

Nov 2nd, 2016
67
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.81 KB | None | 0 0
  1. #include <vector>
  2. #include <iostream>
  3.  
  4. class Drawable {
  5. public:
  6.     virtual void draw() = 0;
  7. };
  8. void Drawable::draw() {
  9.     std::cout << "draw superClass!!" << std::endl;
  10. }
  11.  
  12. class Ship : public Drawable {
  13. public:
  14.     void virtual draw();
  15. };
  16. void Ship::draw() {
  17.     std::cout << "draw ship!!" << std::endl;
  18. }
  19.  
  20. class Enemy : public Drawable {
  21. public:
  22.     void virtual draw();
  23. };
  24. void Enemy::draw() {
  25.     std::cout << "enemy ship!!" << std::endl;
  26. }
  27.  
  28. int main() {
  29.     std::vector<Drawable*> drawables;
  30.     drawables.push_back(new Ship());
  31.     drawables.push_back(new Enemy());
  32.     for (std::vector<Drawable*>::iterator itr = drawables.begin(), end = drawables.end();
  33.         itr != end; ++itr) {
  34.         // use -> syntax for calling when we have a pointer to an object
  35.         (*itr)->draw(); // calls every object in drawables that has draw()
  36.     }
  37. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement