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

Constructors and destructors


The constructor in your C++ code is a simple little function that runs once when the C++ object is first created. The destructor runs once when the C++ object is destroyed. Say we have the following program:

#include <iostream>
#include <string>
using namespace std;
class Player
{
private:
  string name;  // inaccessible outside this class!
public:
  string getName(){ return name; }
// The constructor!
  Player()
  {
    cout << "Player object constructed" << endl;
    name = "Diplo";
  }
  // ~Destructor (~ is not a typo!)
  ~Player()
  {
    cout << "Player object destroyed" << endl;
  }
};

int main()
  {
    Player player;
    cout << "Player named '" << player.getName() << "'" << endl;
  }
  // player object destroyed here

So here we have created a Player object. The output of this code will be as follows:

Player object constructed
Player named 'Diplo'
Player object destroyed

The first thing that happens...