You would never write TimeStamp theTimeStamp = malloc();
in C++.
First, because malloc
is from C and should really not be used in C++. Second, it is unaware of its context and needs a parameter to specify how much memory it must allocate, and returns an untyped pointer which you'd need to cast.
Instead you'd e.g. write
TimeStamp * theTimeStamp = new TimeStamp();
See - that's very similar to Java. Notice the *
in there? That's for specifying that theTimeStamp
is a pointer (in Java, every variable of a user-defined type is a pointer/reference, so you don't have to care about explicitly stating this).
In C++, however, you can choose whether you want
- C++ to automatically handle the creation and destruction with the variable scope (i.e., without the
*
, as is done in your first code example). This means however, that as soon as theTimeStamp
goes out of scope (i.e. usually at the end of the block where the variable is defined), the variable will be destroyed automatically.
- Or if you want to do the dynamic memory allocation yourself (the default case in Java) - but in contrast to Java, you'd also have to care about the deletion of the object yourself in C++.
This having to take care about deletion "manually" is why in C++ usually such raw pointers are not used directly, but instead so called smart pointer types, e.g. std::shared_ptr
from the new C++11 standard. They spare you the chore of having to do the deletion manually (and probably forgetting about it in many cases). There are other smart pointer types as well; the shared_ptr
however provides the closest resemblance to what Java does - you can assign a shared_ptr
to another, thereby keeping the object it points to alive, and only when the last of the shared pointer's pointing to an object is destroyed, will the object pointed to also be destroyed.
Whenever you can, it is however preferable in C++ to refrain from using pointers at all, and instead using automatically allocated variables.