Constructors and Destructors
In the last lesson, each lamp was created first and its members were set afterwards, one line at a time. It is easy to forget one of those lines. A constructor fixes this. It is a special method that runs automatically when an object is created, and its job is to set up the object.
A constructor has the same name as its class, and it has no return type (not even void):
#include <iostream>
#include <string>
using namespace std;
class Pet {
public:
string name;
Pet(string n) {
name = n;
}
};
int main() {
Pet first("Rex");
Pet second("Mia");
cout << first.name << "\n";
cout << second.name << "\n";
return 0;
}
Output:
Rex
Mia
Pet first("Rex"); creates the object and passes "Rex" to the constructor, which stores it in name. Creating the object and setting it up now happen in one step.
Once a class has a constructor with parameters, you must give those values. Creating a pet without a name does not compile:
#include <iostream>
#include <string>
using namespace std;
class Pet {
public:
string name;
Pet(string n) {
name = n;
}
};
int main() {
Pet other;
return 0;
}
Output:
main.cpp: In function ‘int main()’:
main.cpp:15:9: error: no matching function for call to ‘Pet::Pet()’
Pet::Pet() means a Pet constructor with no parameters. The class does not have one, so the compiler stops. This is useful: a pet without a name can never exist.
Destructors
A destructor is the opposite of a constructor. It runs automatically when an object is removed. Its name is the class name with a ~ in front. This version of Pet prints a message in both, so you can see when they run:
#include <iostream>
#include <string>
using namespace std;
class Pet {
public:
string name;
Pet(string n) {
name = n;
cout << name << " arrives" << "\n";
}
~Pet() {
cout << name << " leaves" << "\n";
}
};
int main() {
Pet first("Rex");
Pet second("Mia");
cout << "main ends" << "\n";
return 0;
}
Output:
Rex arrives
Mia arrives
main ends
Mia leaves
Rex leaves
Nothing in main calls ~Pet(). When main ended, both objects were removed and their destructors ran by themselves. They ran in the reverse order of creation: Mia was created last, so Mia left first.
Printing a message is only a way to see the timing. The real job of a destructor is to clean up, for example to give back heap memory with delete. This is how a vector frees its memory without you writing delete: its destructor does it.
Most classes you write need a constructor. You only need a destructor when the object has something to clean up.
In the exercise, write the constructor of a Player class that takes a name and a starting score.