11.07.2015 Views

tYSR20

tYSR20

tYSR20

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

186Part III: Introduction to Classes}// wait until user is ready before terminating program// to allow the user to see the program resultssystem(“PAUSE”);return 0;The program declares a variable s of type Student. It then goes on to declarea pointer variable pS of type pointer to a Student object, also writtenas Student*. The program initializes the value of one of the data members ins. It then precedes to assign the address of s to the variable pS. Finally, itrefers to the same Student object, first using the object’s name, s, and thenusing the pointer to the object, pS. I explain the strange notation pS->gpa; inthe next section of this chapter.Dereferencing an object pointerBy analogy of pointers to simple variables, you might think that the followingrefers to the GPA of student s:int main(int argc, char* pArgs[]){// the following is incorrectStudent s;Student* pS = &s; // create a pointer to s// access the gpa member of the object pointed at by pS// (this doesn’t work)*pS.gpa = 3.5;}return 0;As the comments indicate, this doesn’t work. The problem is that the dotoperator (.) is evaluated before the pointer (*).Note: The * operator is often referred to as the splat operator — not a popularterm with insects.C++ programmers use parentheses to override the order in which operationsare performed. For example, the parentheses force addition to be performedbefore multiplication in the following expression:int i = 2 * (1 + 3); // addition performed// before multiplicationParentheses have the same effect when applied to pointer variables:int main(int argc, char* pArgs[]){

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!