-2

let's say if this is my code

class Rational
{
    public:
        Rational (Rational &copyObject);
        Rational add (Rational rhs);
    private:
        int mNum;
        int mDen;
};
Rational :: Rational (Rational &copyObject)
{
    this->mNum = copyObject.mNum;
    this->mDen = copyObject.mDen;
}
Rational Rational:: add (Rattional rhs)
{
    this->mNumerator = (this->mNumerator * rhs.mDenominator) + 
                       (rhs.mNumerator * this->mDenominator);

    this->mDenominator = this->mDenominator * rhs.mDenominator;

    return *this;
}

int main (void)
{
    Rational r1(10,3), r2 (20,3) //let just assume I have a constructor for initialize
    r1.add(r2);
}

I'm not quite sure what does Rational :: Rational (Rational &copyObject) do
Does it mean that if I don't have that function, I will make a copy of r2, and if I have that function I will connect the local variable in Rational Rational:: add (Rattional rhs) to r2 in main()?

1 more thing, how does the compiler know when to call that function?

I'm new to c++, please explain as easiest as you can.
Thank you!

  • 1
    In spite of the "what does pass by reference really do" question title, the real question here **seems** to be "[What is a copy constructor?](http://stackoverflow.com/questions/2168201)" – Drew Dormann Feb 20 '15 at 21:39

1 Answers1

0

Its a constructor that takes a Rational and makes a copy of it (unlike the constructor you assume exists, that takes 2 integers). So, for example, you could have Rational r3(r2); to make a copy of r2.

Scott Hunter
  • 48,888
  • 12
  • 60
  • 101