PHYCS 6730 Lab Exercise: Pass Through Pointers

In these exercises we play with pointers to class objects and with casting. We illustrate the void pass through pointer, a device used in this week's assignment to solve the problem of passing arbitrary parameter values through an intermediate canned procedure.

Exercise 1 Examining the Code

See the code in ~p6730/exercises/pointers/passthru.cc. Compile it and run it. What is the functional relationship between the last value printed and the values of a, b, and y?

Exercise 2. Playing with the arrow operator

The code prints out the values of a and b after they are placed in the object p, an instance of the class SomeParams. For the class object itself, the member values are accessed with the dot . operator. For pointers to a class object, we use the arrow -> operator. Add two print statements to print the same member values, but access the printed values with the arrow operator from the pointer ptr to the object p. In your answer file, put the statements you used.

Exercise 3. Casting

The pointer to the object SomeParams is cast as a void pointer and then passed through the function some_canned. We use void because it is neutral, generic, and must be recast before we can access the values to which it points. The C++ expression for converting any pointer ptr to a void pointer is
   reinterpret_cast<void *>(ptr)
The C style for casting (also works in C++) is
  (void *)ptr
To get a pointer to a different type, replace void with the desired type. C++ provides other casts, but this is the one to use in this case.

Normally the procedure some_canned would have been compiled separately and doesn't know anything about the parameters, nor does it touch them - it just passes them blindly through to the supplied function func. The supplied function recasts the void pointer to the correct original type. It is up to us to be sure we recast to the original type. The compiler can't check.

This sort of casting defeats the compiler's ability to do strong type checking. That is, with this device we can cast a pointer so it points to anything we like and suffer the consequences if we make a mistake. For example, we can change a pointer to a double into a pointer to a float. But then when we try to get the floating point value to which it points, we get garbage. The compiler has no way of protecting us from such foolishness. So one should cast pointers only when absolutely necessary.

Change the name of the class from SomeParams to NewParams and delete the unused integer member i. Make appropriate changes throughout the code, so the new code compiles and gives the same results. What procedures did you have to change? Did you make any changes to the procedure some_canned? (You shouldn't have.)

List the changes in your answer file.