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.
class Car {
public:
std::string brand;
Car(std::string b) : brand(b) {}
};
int main() {
Car c("Honda");
std::cout << c.brand;
}HondaThe 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.
