fork download
  1. #include <iostream>
  2.  
  3. struct Coord{
  4. int x = 1;
  5. int y = 1;
  6. void printCoord(){
  7. std::cout << "X: " << x << " Y: " << y << std::endl;
  8. }
  9. };
  10.  
  11. class Base{
  12.  
  13. public:
  14. Coord myCoord;
  15. Base(Coord &coord): myCoord(coord){} // How do I modify this line so Base gets a copy of myCoord?
  16. virtual void updateCoord(int x, int y){};
  17.  
  18. };
  19.  
  20. class Derived : public Base {
  21.  
  22. public:
  23. Derived(Coord &coord): Base(coord){} // Or possibly this line?
  24. virtual void updateCoord(int x, int y){
  25. myCoord.x = x;
  26. myCoord.y = y;
  27. std::cout << "Updated to:" << std::endl;
  28. myCoord.printCoord();
  29. }
  30. };
  31.  
  32. int main(){
  33. Coord myCoord;
  34. Base *baseptr;
  35. Derived d(myCoord);
  36. baseptr = &d;
  37.  
  38. std::cout << "Before update:" << std::endl;
  39. myCoord.printCoord();
  40. baseptr->updateCoord(2,2);
  41. std::cout << "After update:" << std::endl;
  42. myCoord.printCoord();
  43.  
  44. return 0;
  45. }
Success #stdin #stdout 0.01s 5304KB
stdin
Standard input is empty
stdout
Before update:
X: 1 Y: 1
Updated to:
X: 2 Y: 2
After update:
X: 1 Y: 1