All, being brief as possible, I’m working on an exercise from C++ Primer Plus Sixth Ed. by Stephen Prata. Chapt 10 Ex 6 for those playing along at home. I wasn’t sure what the exercise was asking. I found someone online who had done the exercises. I thought seeing the program in action, I’d understand the requirement and recreate my own. The program I downloaded works perfectly. My lack of understanding of why is works is my issue. I’m hoping someone here can clear up what I’m not understanding.
MOVE.H
class Move{
private:
double x;
double y;
public:
Move(double a = 0, double b = 0); // sets x, y to a, b
void showmove() const;
Move add(const Move & m) const;
void reset(double a = 0, double b = 0); // resets x,y to a, b
};
MOVE.CPP (there are other class methods that deal with display and reset. I excluded them to conserve space.)
Move::Move(double a, double b)
{ x = a; y = b;}
Move Move::add(const Move & m) const
{
double m_x, m_y;
m_x = this-\>x + m.x;
m_y = this-\>y + m.y;
Move newMove(m_x, m_y);
return newMove;
}
MAIN.CPP (There of other line items for display etc.)
Move move1; //Nothing sent so defaults to (x=0,y=0)per the constructor
Move move2(1.5, 2.5); // constructor set move2 x =1.5 & y=2.5
Move move3(1.5, 2.1); // constructor set move3 x=1.5 & y=2.1
Move move4(move2.add(move3)); // this is where my confusion lies.
When creating move4, I expected the constructor to look for nothing being sent or a combination of 2 doubles. Move2::add returns a reference or address of a newly created Move class called newMove. How does the constructor of move4 know to extract the x and y from newMove of class move2. The program works as expected. Move4 X=3 and Y=4.6. I’m obviously missing something. One of the downsides to learning without a teacher / tutor. Thanks.
How does the constructor of move4 know to extract the x and y from newMove of class move2.
move4's construction is invoking the class's copy constructor.
The declaration for a copy constructor would look like: Move(const Move& other);
If you don't define a copy constructor, the compiler will automatically generate one for you, where it does a "shallow"* copy of each data member of the class.
*This doesn't matter for your case, but when you start to deal with pointers, only the pointer itself will be copied; not the memory it points to.