fork download
  1. #include <iostream>
  2. #include <vector>
  3.  
  4. struct parent
  5. {
  6. virtual ~parent() = default;
  7. virtual void foo() = 0;
  8. };
  9.  
  10. struct Child : parent
  11. {
  12. Child(int n) : n(n) {}
  13. void foo() override { std::cout << n << std::endl; }
  14. int n;
  15. };
  16.  
  17. class Grid{
  18. public:
  19. Grid() : col(10), row(10), grid(col * row, nullptr) {}
  20.  
  21. parent* operator() (std::size_t x, std::size_t y) const {
  22. if (col <= x || row <= y) { throw std::runtime_error("Invalid arguments"); }
  23. return grid[y * col + x];
  24. }
  25.  
  26. parent*& operator() (std::size_t x, std::size_t y) {
  27. if (col <= x || row <= y) { throw std::runtime_error("Invalid arguments"); }
  28. return grid[y * col + x];
  29. }
  30.  
  31. private:
  32. int col;
  33. int row;
  34. std::vector<parent*> grid;
  35. };
  36.  
  37.  
  38. int main() {
  39. Grid b;
  40. Child c(1);
  41. Child c2(2);
  42.  
  43. b(1,1) = &c;
  44. b(1,4) = &c2;
  45.  
  46. b(1,1)->foo(); //calls the first Childs foo()
  47. b(1,4)->foo(); //calls the second Childs foo()
  48. }
Success #stdin #stdout 0s 15240KB
stdin
Standard input is empty
stdout
1
2