Sams Teach Yourself C++ in 21 Days

(singke) #1
Working with Advanced Functions 309

10


This is more elegant, but raises the question, “Why create a temporary object at all?”
Remember that each temporary object must be constructed and later destroyed—each of
these is potentially an expensive operation. Also, the object ialready exists and already
has the right value, so why not return it? This problem can be solved by using the this
pointer.

Using the thisPointer ..................................................................................


Thethispointer is passed to all member functions, including overloaded operators such
as operator++(). In the listings you’ve been creating,thispoints to i, and if it is deref-
erenced it returns the object i, which already has the right value in its member variable
itsVal. Listing 10.11 illustrates returning the dereferenced thispointer and avoiding the
creation of an unneeded temporary object.

LISTING10.11 Returning the thisPointer


1: // Listing 10.11 - Returning the dereferenced this pointer
2:
3: #include <iostream>
4:
5: using namespace std;
6:
7: class Counter
8: {
9: public:
10: Counter();
11: ~Counter(){}
12: int GetItsVal()const { return itsVal; }
13: void SetItsVal(int x) {itsVal = x; }
14: void Increment() { ++itsVal; }
15: const Counter& operator++ ();
16:
17: private:
18: int itsVal;
19: };
20:
21: Counter::Counter():
22: itsVal(0)
23: {};
24:
25: const Counter& Counter::operator++()
26: {
27: ++itsVal;
28: return *this;
29: }
30:
31: int main()
32: {
Free download pdf