Constructors
beginnerA constructor is a special member function that runs automatically when an object is created.
Purpose
- Initialize member variables
- Allocate resources
- Set up the object in a valid state
Syntax
Types of Constructors
- Default: Takes no arguments (Person())
- Parameterized: Takes arguments (Person(string n, int a))
- Copy: Creates a copy of another object (Person(const Person& other))
Initializer List
- Preferred way to initialize members
- More efficient than assignment in the constructor body
- Required for const and reference members
Constructor Rules
- Same name as the class
- No return type (not even void)
- Called automatically when object is created
- Can be overloaded (multiple constructors with different parameters)
Key takeaway: A constructor runs automatically when an object is created โ use initializer lists for efficient, safe member initialization.