Dynamic memory allocation
Now, let's try allocating a Player
object dynamically. What does that mean?
We use the new
keyword to allocate it!
int main() { // "dynamic allocation" – using keyword new! // this style of allocation means that the player object will // NOT be deleted automatically at the end of the block where // it was declared! Player *player = new Player(); } // NO automatic deletion!
The output of this program is as follows:
Player born
The player does not die! How do we kill the player? We must explicitly call delete
on the player
pointer.
The delete keyword
The
delete
operator invokes the destructor on the object being deleted, as shown in the following code:
int main() { // "dynamic allocation" – using keyword new! Player *player = new Player(); delete player; // deletion invokes dtor }
The output of the program is as follows:
Player born Player died
So, only "normal" (or "automatic" also called as non-pointer...