Search code examples
c++pass-by-reference

Pass by reference to base class constructor from derived class constructor


I would like to include a reference of a struct, Coord, within a class, Base, from the initializer list of derived class, Derived. When I pass the instance of Coord to the Derived class constructor, a new instance of Coord is created - or at least I assume this is what is happening because I cannot update my coord object from the derived class.

Am I breaking some sort of rule by passing a reference in this way? Or just doing it incorrectly?

See Example:

#include <iostream>

struct Coord{
  int x = 1;
  int y = 1;
  void printCoord(){
    std::cout << "X: " << x << " Y: " << y << std::endl;
  }
};

class Base{

  public:
  Coord myCoord;
  Base(Coord &coord): myCoord(coord){} // How do I modify this line so Base gets a copy of myCoord?
  virtual void updateCoord(int x, int y){};

};

class Derived : public Base {

  public:
  Derived(Coord &coord): Base(coord){} // Or possibly this line?
  virtual void updateCoord(int x, int y){ 
    myCoord.x = x;
    myCoord.y = y;  
    std::cout << "Updated to:" << std::endl;
    myCoord.printCoord();
  }
};

int main(){
  Coord myCoord;
  Base *baseptr;
  Derived d(myCoord);
  baseptr = &d;

  std::cout << "Before update:" << std::endl;
  myCoord.printCoord();
  baseptr->updateCoord(2,2);
  std::cout << "After update:" << std::endl;
  myCoord.printCoord();

  return 0;
}

I expect to get the following output:

Before update:
X: 1 Y: 1
Updated to:
X: 2 Y: 2
After update:
X: 2 Y: 2

But instead get:

Before update:
X: 1 Y: 1
Updated to:
X: 2 Y: 2
After update:
X: 1 Y: 1

Solution

  • Change the declaration of myCoord in Base to be a reference:

    class Base{
    
      public:
      Coord& myCoord;  // reference declaration
      Base(Coord &coord): myCoord(coord){} // How do I modify this line so Base gets a copy of myCoord?
      virtual void updateCoord(int x, int y){};
    
    };
    

    Then myCoord will be the same reference as your instance of Coord in main.