OOPortal OOPortal

Operator Overloading  «Prev 

Pointer to class member

Types of operators that can be overloaded

In C++, 1) a pointer to a class member is distinct from a 2) pointer to a class. A pointer to class member has type T::*, where T is the class name.
C++ has two operators that act to dereference a pointer to a class member. The pointer to member operators are:
  1. .* and
  2. ->*
Think of x.*ptr_mem as first dereferencing the pointer to obtain a member variable and then accessing the member for the designated x.
Here is an example of the difference between .* and ->*:

class trio {
   int a, b, c;
} x, y, *q = &y;

int trio::*p = &trio::b;
x.*p     //gets x.b
q ->*p   //gets y.b

Remember: ->* can be overloaded, while .* cannot be overloaded.

Pointer Arithmetic and Arrays

To move through an array of an indeterminate size that was created using malloc, use code similar to the following:
int * nArray, ptArray;
nArray = (int *) malloc (sizeof (int) * 101);
/* Additional code here to set values for items 0 to 99 */
nArray[100] = -1;
// Set 100th value to default ’end of array’
ptArray = nArray;
while (*ptArray != -1){
 ptArray+ +; // Move through the memory block

In the previous code snippet, ptArray+ + moves through the memory block (pointer arithmetic), and *ptArray accesses the actual value and tests it against –1. If the comparison succeeds, that value must be the last element in the array. This allows you to create an intlen function, similar to the strlen function, to return the number of integers in the array. The difference between explicitly accessing each element and testing it for an end-of-array value is that you can return the number of used (or effective) items in the array. If you take the size of the memory block and divide it by the size of an element, this will return the total number of elements in the array, whether or not they are used.