Hello, I'm new to both to this site and to C++, I've started reading the book 'C++ Without Fear - 2nd edition' a couple of week ago. when I reached chapter 12 (which is about constructors) I got stuck on the subject of copy constructors, and I seek your help!
(Example 12.3 from page 325 to page 329)
This is the Fraction class declaration.
Code:
class Fraction
{
private:
int num;
int den;
public:
Fraction() {set(0, 1);} // Default constructor.
Fraction(int n, int d) {set(n, d);} // (int, int) constructor.
Fraction(Fraction const &src); // Copy constructor.
void set(int n, int d) {num = n; den = d; normalize();}
int get_num() {return num;}
int get_den() {return den;}
Fraction add(Fraction other);
Fraction mult(Fraction other);
private: // Member functions (Private).
void normalize();
int gcf(int a, int b);
int lcm(int a, int b) {return (a * b) / gcf(a, b);}
};
This is the copy constructor definition.
Code:
Fraction::Fraction(Fraction const &src)
{
cout << "Now calling copy constructor!" << endl;
num = src.num;
den = src.den;
}
This is the main() function.
Code:
int main()
{
Fraction f1(3, 4);
Fraction f2(f1);
Fraction f3 = f1.add(f2);
cout << "The value of f3 is ";
cout << f3.get_num() << "/";
cout << f3.get_den() << endl;
return 0;
}
In the book it is said that the next line of code should call the copy constructor once (printing the "Now calling copy constructor!") Which it dose!
However the book also say that the next line of code should call the copy constructor three times!
first time when the object f2 is passed as an argument,
a second time when a new object is passed back as a return value,
and a third time when that object is copied to the f3 object.
Code:
Fraction f3 = f1.add(f2);
But when I run this program, it prints the above message only twice (instead of 4 times!!).
I was thinking it must be the compiler optimizing the add member function, making it pass references instead of a copy of the object,
but I don't really have any idea if I'm right.
Am I making any sense or am I way off?
I'd really appreciate if anyone can help me understand how and why the thing I described happens!
(Btw I'm using both Code::Blocks and Dev-C++ IDE)
Thanks ahead C.
P.S. Sorry for my English!