In C++, I have two block of codes like this:
Base *base = new Base();
base->showName();
And:
Base base;
base.showName();
I don't know when do we use pointer and when not? And what's different and what is better?
In C++, I have two block of codes like this:
Base *base = new Base();
base->showName();
And:
Base base;
base.showName();
I don't know when do we use pointer and when not? And what's different and what is better?
The first code you showed is a memory leak.
The second snippet is Java, not C++. The question has been edited to use my suggested code.
Generally though, in C++ you should avoid new
unless you really NEED dynamic lifetime. Instead, write:
Base base;
base.showName();
This is better because
If the object needs to live past the end of the scope, you should be using:
unique_ptr<Base> base(new Base());
base->showName();
Now unique_ptr
will free the memory for you when the unique_ptr
dies, and it's also exception-safe. When you return a unique_ptr
, ownership is transferred to the caller, and he can reap the benefits of automatic cleanup.