Book Image

Learning C++ by creating games with UE4

By : William Sherif
Book Image

Learning C++ by creating games with UE4

By: William Sherif

Overview of this book

Table of Contents (19 chapters)
Learning C++ by Creating Games with UE4
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
2
Variables and Memory
Index

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 type) variable types get destroyed at the end of the block...