Programming and Graphics

(Kiana) #1

174 Introduction to C++ Programming and Graphics


can be replaced by:


pnt->print();

Note the “ASCII art” pointer designation of the arrow:->


“this” communicates the memory address of an object


Let us revisit the algebra class discussed in Section 6.8 and introduce the
member functionprint1defined as:


void algebra::print()
{double * pntx = &x;
string * pntc = &color;
cout << this << " " <<pntx <<""<<pntc << " "<< x
<<""<<color<<endl;
}

Including in the main program the statements:


algebra Z(-0.4);
Z.print1();
algebra * pntZ = &Z;
cout << pntZ << endl;

prints on the screen:


0xbfdb1cc8 0xbfdb1cc8 0xbfdb1cd0 -0.4 red
0xbfdb1cc8

We see thatthisis the memory address of point Z regarded as an object of
the algebra class. Furthermore, the memory address of Z is the same as the
memory address of its first field,Z.x


When a function operates on an object, its memory address is implicitly
passed to the object through the variablethis. In practice,thisis used to
overload the assignation operator and check whether a parameter passed to a
member function is the object itself.


Problems


6.10.1. Illustrate the implicit communication of a member’s memory address
throughthisfor the class of circles discussed in Section 6.7.


6.10.2. What changes are necessary so that the memory address of an algebra
point is the same as the memory address of its color?

Free download pdf