Lesson 134 +10 XP

Constructors

Constructors

A constructor is a special method that runs automatically when an object is created. It sets up the new object - for instance by giving a member its starting value.

Rules of a constructor

  • Its name must match the class name.
  • It has no return type, not even void.
  • It runs automatically the moment you create an object.
class Car {
public:
  string brand;
  Car() {             // constructor, same name as the class
    brand = "Unknown";
  }
};

Using it

int main() {
  Car myCar;       // the constructor runs here
  cout << myCar.brand;   // prints "Unknown"
  return 0;
}

The object is initialized before you use it, so no member is left with a strange value.

Constructors with parameters

A constructor can take arguments to give each object a different starting state:

class Car {
public:
  string brand;
  Car(string b) {
    brand = b;
  }
};

Car myCar("Toyota");   // brand holds "Toyota"

TL;DR

  • A constructor shares the class's name and has no return type.
  • It runs automatically when the object is created.
  • It puts starting values into the new object's members.
  • Parameterized constructors set up each object with arguments.