First, you can do this:
Ball ball;
You now have a local Ball object. It will last until the enclosing code is closed. That is:
cout << "Foo\n";
if (true) {
Ball ball;
}
cout << "Bar\n";
The ball exists only inside those {}
. If you try to use it outside (where the cout of Bar is found), it won't be there. So in many cases, your variables will be alive for the scope of a function call.
void foo() {
Ball ball;
...
}
This is the easiest thing to do, and it probably works for most of your use cases. You probably don't need to worry about pointers for your first pieces of code.
However, if there's a reason you want to really use pointers, you can do this:
void foo() {
Ball * ball = new Ball;
... make use of it
delete ball;
}
If you don't do the delete, you have a memory leak. Unlike Java, C++ doesn't have any sort of garbage collector. You're on your own.
But you can also do this:
void foo() {
std::shared_ptr<Ball> ball = std::make_shared<Ball>();
... use it
... no delete required
}
These are referred to as smart pointers, and the trend in C++ is to use either unique_ptr
or shared_ptr
instead of raw pointers. (Raw pointers are what I did in the previous example.) These work more like C++ objects, where when you lose all the pointers, it knows and deletes the memory for you. This is referred to as RAII (Resource Acquisition Is Initialization), and you're strongly, strongly encouraged to learn it.