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 during object construction is that the constructor actually runs. This prints the line Player object constructed. Following this, the line with the player's name gets printed: Player named 'Diplo'. Why is the player named Diplo? Because that is the name assigned in the Player() constructor.

Finally, at the end of the program, the player destructor gets called, and we see Player object destroyed. The player object gets destroyed when it goes out of scope at the end of main() (at } of main).

So what are constructors and destructors good for? Exactly what they appear to be for: setting up and tearing down of an object. The constructor can be used for initialization of data fields and the destructor to call delete on any dynamically allocated resources (we haven't covered dynamically allocated resources yet, so don't worry about this last point yet).

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.128.226.255