C++ Constructors
A constructor is a special method that runs automatically the moment an object is created. It is the perfect place to give an object's attributes their starting values, so no object is ever left with garbage data.
In earlier examples you created an object and then set each attribute one line at a time. A constructor lets you do all of that setup in a single step, right when the object is born. This makes your code shorter and guarantees every object starts in a valid state.
Writing a Constructor
A constructor has the exact same name as the class and has no return type, not even void. It is called automatically, so you never call it by name yourself.
A basic constructor
#include <iostream>
#include <string>
using namespace std;
class Car {
public:
string brand;
int year;
Car() { // constructor
brand = "Unknown";
year = 2000;
}
};
int main() {
Car myCar; // constructor runs here
cout << myCar.brand << " " << myCar.year;
return 0;
}Constructors With Parameters
A constructor can take parameters, letting you pass in the starting values when you create the object. This is the most common and most useful form.
A parameterized constructor
#include <iostream>
#include <string>
using namespace std;
class Student {
public:
string name;
int score;
Student(string n, int s) { // constructor with parameters
name = n;
score = s;
}
};
int main() {
Student a("Maya", 92); // pass values on creation
Student b("Leo", 78);
cout << a.name << ": " << a.score << endl;
cout << b.name << ": " << b.score << endl;
return 0;
}- A constructor's name must match the class name exactly.
- A constructor has no return type.
- It runs automatically when an object is created.
- You can pass starting values through the constructor's parameters.
Constructor at a glance
Exercise: C++ Constructors
What is a defining characteristic of a constructor in C++?