A constructor is a special method that runs automatically when an object is created. You use it to set initial values while the object is being built. A constructor's name has to match the class name.
cpp
#include <iostream>
#include <string>
using namespace std;
class Car {
public:
string brand;
int year;
Car(string b, int y) {
brand = b;
year = y;
}
void show() {
cout << brand << " - " << year;
}
};
int main() {
Car myCar("Toyota", 2024);
myCar.show();
return 0;
}Car myCar("Toyota", 2024); — writing this to create an object automatically calls the constructor, which stores the parameters into the attributes.
You should see
Toyota - 2024Info
A constructor never gets a return type. Write void Car() and it's no longer a constructor.