2.11. Copy Constructors and Assignment Operators

[ fromfile: copyassign.xml id: copyassign ]

Example 2.16. src/lifecycle/copyassign/fraction.h

[ . . . . ]
class Fraction {
 public:
    Fraction(int n, int d) ;                        1
    Fraction(const Fraction& other) ;               2
    Fraction& operator=(const Fraction& other) ;    3
    Fraction multiply(Fraction f2) ;
    static QString report() ;
 private:
    int m_Numer, m_Denom;
    static int s_assigns;
    static int s_copies;
    static int s_ctors;
};
[ . . . . ]

1

Regular constructor

2

Copy constructor

3

Copy assignment operator


Example 2.17. src/lifecycle/copyassign/fraction.cpp

[ . . . . ]
int Fraction::s_assigns = 0;     1
int Fraction::s_copies = 0;
int Fraction::s_ctors = 0;

Fraction::Fraction(const Fraction& other)
   :  m_Numer(other.m_Numer), m_Denom(other.m_Denom) {
   ++s_copies;
}

Fraction& Fraction::operator=(const Fraction& other) {
    if (this != &other) {        2
        m_Numer = other.m_Numer;
        m_Denom = other.m_Denom;
        ++s_assigns;
    }
    return *this;                3
}
[ . . . . ]

1

Static member definitions.

2

operator=() should always do nothing in the case of self- assignment.

3

operator=() should always return *this, to allow for chaining i.e. a=b=c.


Example 2.18. src/lifecycle/copyassign/copyassign.cpp

#include <QTextStream>
#include "fraction.h"

int main() {
    QTextStream cout(stdout);
    Fraction twothirds(2,3);                1
    Fraction threequarters(3,4);
    Fraction acopy(twothirds);              2
    Fraction f4 = threequarters;            3
    cout << "after declarations - " << Fraction::report();
    f4 = twothirds;                         4
    cout << "\nbefore multiply - " << Fraction::report();
    f4 = twothirds.multiply(threequarters); 5
    cout << "\nafter multiply - " << Fraction::report() << endl;
    return 0;
}

1

Using 2-arg constructor.

2

Using copy constructor.

3

Also using copy constructor.

4

Assignment.

5

Several objects are created here.


[Important]Question

As you can see, the call to multiply creates three Fraction objects. Can you explain why?