Examples of Temporary Objects


/************************************************************************
*

The following example shows two expressions in which temporary objects xre constructed:

                                                                        *
************************************************************************/

class Y
{
public:
      Y(int);
      Y(Y&);
      ~Y();
};
Y add(Y y) { /* ... */ }

void main ()
{
      Y obj1(10);
      Y obj2 = add(Y(5));       // one temporary created
      obj1 = add(obj1);         // two temporaries created
}

/************************************************************************
*

In the above example, a temporary object of class type Y is created to construct Y(5) before it is passed to the function add(). Because obj2 is being constructed, the function add() can construct its return value directly into obj2, so another temporary object is not created. A temporary object of class type Y is created when obj1 is passed to the function add(). Because obj1 has already been constructed, the function add() constructs its return value into a temporary object. This second temporary object is then assigned to obj1 using an assignment operator.

                                                                        *
************************************************************************/