Setting every member by hand after creating an object is tiring, and easy to forget. A constructor is a special method that runs automatically when an object is created. It has the same name as the class and no return type:
#include <iostream>
#include <string>
using namespace std;
class Dog {
public:
string name;
int age;
Dog(string n, int a) {
name = n;
age = a;
cout << "A dog called " << name << " was created\n";
}
};
int main() {
Dog a("Rex", 3);
Dog b("Bella", 5);
cout << b.name << " is " << b.age << "\n";
return 0;
}Output
A dog called Rex was created A dog called Bella was created Bella is 5
The member initializer list
C++ has a neater way to set members in a constructor: a colon after the brackets, then each member with its starting value. This is the style most C++ programmers use:
#include <iostream>
#include <string>
using namespace std;
class Book {
public:
string title;
int pages;
Book(string t, int p) : title(t), pages(p) {}
};
int main() {
Book b("Dune", 412);
cout << b.title << ": " << b.pages << " pages\n";
return 0;
}Output
Dune: 412 pages
Several constructors
Like functions, constructors can be overloaded. A constructor with no parameters is called the default constructor:
#include <iostream>
#include <string>
using namespace std;
class Player {
public:
string name;
int lives;
Player() : name("Unknown"), lives(3) {}
Player(string n) : name(n), lives(3) {}
Player(string n, int l) : name(n), lives(l) {}
};
int main() {
Player a;
Player b("Mario");
Player c("Luigi", 5);
cout << a.name << " " << a.lives << "\n";
cout << b.name << " " << b.lives << "\n";
cout << c.name << " " << c.lives << "\n";
return 0;
}Output
Unknown 3 Mario 3 Luigi 5
Remember: If you write any constructor yourself, C++ stops giving you the free default one. Add
ClassName() {}yourself if you still need to create objects without arguments.