From where did you got that (bad) C++ code and did you even compiled both versions?
A much better version would use
std::string
instead of char arrays. Then it can be converted to Java using the Java
String
class. So change your members to that type in your Java class.
Because you are setting strings of existing objects and the members are private, you must also provide
setFirstName()
and
setLastName()
functions (in the C++ and Java version) or make the string members public (which would be bad style).
[EDIT]
Using
std::string
in the C++ version avoids handling the buffers yourself and reduces the source code: No allocation and deleting is required and the default created destructor will call the destructors of the string members so that there is no need to implement a destructor. While there might be reasons to do such sometimes, it is usually not necessary with strings. Just keep it simple.
Some notes when using your own C++ memory allocation:
- There is no need to check for
NULL
pointers in the constructor. The values are undefined there until set.
- There is no need to check for
NULL
pointers with delete
.
- There is no need to set the pointers finally to
NULL
in the destructor.
The above explains why I wrote of bad code. Note also that the get functions should be const and return const chars:
const char *getFirstName() const { return firstName; }
const char *getFirstName() const { return firstName.c_str(); }
Java is a garbage collected language so that there is no need for a destructor or releasing of objects. While it would be possible to create your own char based objects to hold strings it is even more useless than with C++ (for the same reasons and it is rather uncommon with Java).
The stream operations can't be simply converted to Java. But I think your solution fits so that I did not provide a solution.
But you might create a function that prints the values out.
[/EDIT]