A constructor is a special member function of a class that is automatically invoked when an object of the class is created. Its primary purpose is to initialize the objects of the class. In C++, the constructor's name must match the class name and it does not specify a return type.
Characteristics of Constructors:
- Automatic Invocation: When an object is created, the constructor is automatically executed.
- No Return Type: The constructor does not return a value and does not specify a return type.
- Parameter Acceptance: The constructor can accept parameters, which allows for greater flexibility in object initialization.
Types of Constructors:
- Default Constructor: If no parameters are provided, this constructor is called.
- Parameterized Constructor: A constructor with parameters that provides more detailed initialization.
- Copy Constructor: A constructor that initializes a new object using an existing object of the same class.
Example Code:
cpp#include <iostream> using namespace std; class Car { public: string brand; int year; // Default constructor Car() { brand = "Unknown"; year = 0; } // Parameterized constructor Car(string x, int y) { brand = x; year = y; } // Copy constructor Car(const Car &obj) { brand = obj.brand; year = obj.year; } void display() { cout << "Brand: " << brand << ", Year: " << year << endl; } }; int main() { // Using default constructor Car car1; car1.display(); // Using parameterized constructor Car car2("Toyota", 2015); car2.display(); // Using copy constructor Car car3 = car2; car3.display(); return 0; }
In this example, the Car class has three constructors: a default constructor, a parameterized constructor, and a copy constructor. These constructors are used to initialize the member variables of the Car class when objects are created.
In this way, constructors ensure that whenever an object of the class is created, its state is well-defined and initialized. This is a fundamental approach to implementing encapsulation and managing the state of the class, which is a key concept in object-oriented programming.