Thuta Learning
AdvancedProgrammingbeginner

Constructors

Relax. We'll talk through this in plain words — no textbook voice.

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 - 2024

Info

A constructor never gets a return type. Write void Car() and it's no longer a constructor.

Easy traps

  • Giving a constructor parameter the same name as an attribute can cause confusion. It's worth learning to use an initializer list for this down the line.
Constructors | Thuta Learning