POINTERS AND REFERENCES TO OBJECTS
Using pointers, and particularly references to class objects, is very important in object-oriented programming and in the specification of function parameters. Class objects can involve considerable amounts of data, so using the pass-by-value mechanism for objects can be very time-consuming and inefficient because each object that is passed to a function in this way will be copied. Using reference parameters avoids this overhead and reference parameters are essential to some operations with classes. As you’ll see, you can’t write a copy constructor without using a reference parameter.
Pointers to Objects
You declare a pointer to an object in the same way that you declare other pointers. For example, a pointer to objects of type CBox is declared in this statement:
CBox* pBox(nullptr); // Declare a pointer to CBox
You can use this to store the address of a CBox object in an assignment in the usual way, using the address operator:
pBox = &cigar; // Store address of CBox object cigar in pBox
As you saw when you used the this pointer in the Compare() member function, you can call a function using a pointer to an object. You can call the Volume() function for the pointer pBox like this:
cout << pBox->Volume(); // Display volume of object pointed to by pBox
This uses the indirect member selection operator. This is the typical notation used by most programmers for this kind of operation, so from now on, I’ll use it universally.
Get Ivor Horton's Beginning Visual C++ 2012 now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.