Pages

Monday, September 19, 2011

Sample Code : Constant functions and temporary objects | Return Optimization

1. Constant funtions with temporary objects :
it tells that temporary objects are by default constant in nature, that their values cannot be changed. and so only constant functions can be called using temporary objects.


2. bruce eckel says about return value optimization : that returning by values just by making an explicit constructor call.

This doesnt create a local object (if i were use Integer a; return a;) and so
no call of copy constructor at the time of return object

its a direct creation of temp object in the return address and compiler knows that u r creating this object only for return purpose and nothing else.



Ref : Sections : 
1. Return by value as constants, Pg 533
2. The return optimization, pg 534
Chp 12 Operator Overloading, : Thinking in C++, second edition, volume 1


#include
using namespace std;
#define about \
"this program demonstrates \
\n 1. that only constant functions should be and can be called from temporary objects \
\n 2. return value optimization : while returning object by value using operator+, \
\n this way doesnt call any form of constructor"




class Integer
{
int i;
public:
Integer(int i):i(i){}
~Integer(){
cout<<"\ndestructor called:"<
}


const Integer operator+(const Integer & right)
{
return Integer(i + right.i);
}
void g()
{
cout<<"gOnce called g-one"<
}
int getValue()const
{ return i;
}

};


int main()
{
Integer a(2), b(4);
// ! (a+b).g(); //this line is a compile time error because g() in a non const function
cout <
cout<<(a+b).getValue()<
return 0;
}

No comments:

Post a Comment