C++ ยท Chapter 33 of 49

C++ Constructors

A constructor is a special method with the same name as the class, automatically called when an object is created, used to initialise its members. A class can have multiple constructors (overloaded) with different parameter lists.

If you don't define any constructor, the compiler provides a default one that does nothing special; but as soon as you define one constructor, the compiler stops generating the default automatically.

Defining a constructor

`Car(std::string b) { brand = b; }` runs automatically when a `Car` object is created with an argument. There is no return type, not even void.

Initialiser lists and destructors

`Car(std::string b) : brand(b) {}` is a member initialiser list, often more efficient. A destructor `~Car()` runs automatically when the object is destroyed, useful for cleanup.

Example 1 (cpp)
class Car {
public:
    std::string brand;
    Car(std::string b) : brand(b) {}
};
int main() {
    Car c("Honda");
    std::cout << c.brand;
}
Output
Honda

The constructor runs automatically, setting brand via the initialiser list.

Key points

  • Constructors share the class name and have no return type.
  • They run automatically when an object is created.
  • Initialiser lists (: member(value)) are the efficient way to set fields.
  • A destructor (~ClassName) runs automatically on destruction.
๐Ÿ’ก Note: Defining any constructor disables the compiler-generated default constructor โ€” add one explicitly if you still need it.

๐Ÿ“ Quick Quiz

1. When does a constructor run?

2. What is a constructor's return type?

3. What runs automatically when an object is destroyed?