When you convert a c++ program into Java, perhaps the: greatest number of changes Will be car seed by pointers. Most <#+ code is heavily dependent upon pointers for its operation. You can’t program anything very Significant in C++ without using a pointer. There are four general categories of pointer usage that you will encounter in C++ code.
Additionally, many of the standard bratty functions supported by C++ are holdovers from C. When one of these C-based functions requires the address of an argument, a pointer to the argument is used. Inside-the function, the argument is.then accessed through its pointer.
*To provide a more efficient means of implementing certain conspiratorially indexing. For example, it is often more’efficient to’ sequentially mo~e through an array using a pointer rather than an array While modem compilers implement highly efficient optimizations, pointers can still provide a significant performance boost. the use of pointers to access arrays is ubiquitous in C++ code.
*To support memory action. In C++, when you allocate memory-an address (that is, a pointer) to that memory is returned. This address must be assigned to a pointer variable. Once this has been done, the pointer can point to any part of the allocated memory-or anywhere else, Cor that matter-s-by means of pointer arithmetic. In Java) when an object is allocated by ‘new, a reference to the object is returned. reference must be assigned to.a reference variable of a compatible type. While Java reference variables do implicitly point to the object that was allocated by the new operator, the cannot be manipulated in the same way as C++ pointers. And they cannot point to memory outside of the Java run-time context.
*To provide access to any machine address, possibly to call a ROM routine or to read/write directly to memory. Since Java purposely disallows such actions, this use of pointers has no direct parallel. If you are writing applications, not applets, you can always use Java’s native capabilities , (described in Part One) to gain access to native code routines that would be allowed access to such system resources.
Converting Poitier Parameters
For the most part, it is quite easy to convert a uses pointer parameters into its equivalent Java method. Since Java passes all objects by reference, sometimes the conversion simply requires the removal of C++’s pointer operators. For example, consider this C++ program that reverses the signs of a object, which stores a pair of Cartesian coordinates. The function reverse Sign( ) is passed a pointer.to the Chord object that will be reversed. As you can see. C++’s It:&. and -> pointer operators are used to. perform the operation.
This program can be receded into the following Java version. As you can see, most
of the conversion involves the deletion’of the C++ pointer operators. Since Java passes objects by reference, changes to the parameter automatically affect the argument.