O'Reilly logo

Efficient C++ Performance Programming Techniques by David Mayhew, Dov Bulka

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Object Definition

Say that class Rational is declared as follows:

class Rational
{
friend Rational operator+(const Rational&, const Rational&);
public:
    Rational (int a = 0, int b = 1 ) : m(a), n(b) {}
private:
    int m;  // Numerator
    int n;  // Denominator
};

We can instantiate objects of type Rational in several equivalent ways:

Rational r1(100);              // 1
Rational r2 = Rational(100);   // 2
Rational r3 = 100;             // 3

Only the first form of initialization is guaranteed, across compiler implementations, not to generate a temporary object. If you use forms 2 or 3, you may end up with a temporary, depending on the compiler implementation. Take form 3 for example:

Rational r3 = 100; // 3

This form may lead the compiler to use the Rational::Rational(int, ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required