C++ Class Construct  «Prev  Next»

Variable Memory Allocation - Exercise

Objective: Add three variables to the main() function below, then modify the main() function so it prints out the location of all its variables.

Variable memory allocation exercise Instructions

First, in main(), add the variables c_pair c, char c1, and double x. You can use the where_am_I() function to print out the location of the c_pair variables.

Some system-dependent considerations

The cout function does not interpret the attempts to print predefined data types, such as int or double, correctly on all machine types. On some machines the correct address of double is printed, while on the others, 1 is returned instead. The behavior of a char-type pointer is fairly consistent. C++ interprets a char pointer as a pointer to a string of char, and therefore, when we try to print &c (char * c;), the value of c is displayed instead of its address.
For the address pointers of these predefined data types to be printed correctly, you first need to convert the pointers to type void*. This is done by calling static_cast<void*>(predefined data type variable). Depending on your system, it may not be necessary to convert the pointer of type double to type void*, although you will definitely need to cast any char pointer to type void* to have its address displayed correctly.

C++ Program

This code is also available in a file named this.cpp, which can be found in the compressed course download file available in the resources section.

#include <iostream.h>
//The this pointer
class c_pair {
public:
   void init(char b) { c2 = 1 + (c1 = b); }
   c_pair increment()  { c1++; c2++; return (*this); }
   c_pair* where_am_I() { return this; }
   void print() { cout << c1 << c2 << '\t'; }
private:
   char  c1, c2;
};

int main(){
  c_pair  a, b;    
  a.init('A');
  a.print();
  cout << " is at " << a.where_am_I() << endl;
  b.init('B');
  b.print();
  cout << " is at " << b.where_am_I() << endl;
  b.increment().print();
}

Paste the source code of your program below and click the Submit button when you are ready to submit this exercise.