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...