Learn C++ · lesson 39 of 61 · about 8 minutes
Constructors
Fill the spell book: initialise objects with constructors and member initialiser lists.
What you'll learn
- Write a constructor
- Use a member initialiser list
- Overload constructors
The spell book
Setting a monster's name and health one line at a time works, but it's easy to forget one. A spell should never exist without its name and power, so the Spell class gets a constructor that takes both and stores them the moment the spell is made. A power below 1 is stored as 1. A second constructor takes just a name and passes it on with power 10, so Spell spark("spark"); makes the spell every hero knows.
Set up on creation
A constructor has the class's name and no return type. It runs when an object is created, so every object starts in a valid state.
The member initialiser list after a colon sets members directly:
Pet(std::string n, int h) : name(n), hunger(h) {}
Constructors
#include <iostream>
#include <string>
class Pet {
public:
Pet(std::string n, int h) : name(std::move(n)), hunger(h) {}
explicit Pet(std::string n) : Pet(std::move(n), 5) {}
void status() const { std::cout << name << " hunger " << hunger << "\n"; }
private:
std::string name;
int hunger;
};
int main() {
Pet a("Phoebe", 2);
Pet b("Rex");
a.status();
b.status();
}Output
Phoebe hunger 2
Rex hunger 5Tip
explicit stops a one-argument constructor being used for surprise automatic conversions. It's a good default for single-argument constructors.
Checking on the way in
The initialiser list can do more than copy a value: seconds_(s > 0 ? s : 1) checks it first. Because a constructor is the only way to make the object, no timer can ever start with a bad value.
A timer that never starts below 1 second
#include <iostream>
class Timer {
public:
explicit Timer(int s) : seconds_(s > 0 ? s : 1) {}
int seconds() const { return seconds_; }
private:
int seconds_;
};
int main() {
Timer a(90);
Timer b(-5);
std::cout << a.seconds() << " " << b.seconds() << "\n";
}Output
90 1Now try it yourself
This lesson is free in Codiqo, with 8 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.