Index
Constructor
A constructor in C++ is a special member function of a class that gets automatically called when an object of that class is created. Its primary purpose is to initialize the object’s data members and perform any necessary setup operations. Constructors have the same name as the class and do not have a return type. To create a constructor, use the same name as the class, followed by parentheses ()
Example:
#include <iostream>
using namespace std;
class MyClass {
public:
MyClass() {
cout << "Some Text";
}
};
int main() {
MyClass object;
return 0;
}
Output:
Some Text
Constructor Parameters
Constructor parameters in C++ allow you to initialize an object with specific values at the time of its creation. Here’s the theory behind constructor parameters:
- Initialization: Constructors are special member functions of a class that are automatically called when an object of that class is created. They are primarily used to initialize the object’s data members.
- Parameterized Constructors: Constructors can accept parameters, just like regular functions. These parameters allow you to pass values to the constructor when creating an object.
- Initialization List: Inside the constructor definition, you can use an initialization list to initialize the data members of the class with the values passed as parameters.
- Flexibility: Constructor parameters add flexibility to your classes by allowing you to create objects with different initial states. For example, in a
Car
class, you can pass the brand, model, and year of the car as parameters to the constructor, enabling you to create different cars with different properties. - Constructor Overloading: Like other functions in C++, constructors can also be overloaded. This means you can define multiple constructors with different parameter lists, allowing you to create objects using different initialization options.
- Default Constructor: If you do not define any constructor for a class, C++ automatically generates a default constructor with no parameters. However, once you define a constructor with parameters, the default constructor is no longer generated unless you explicitly define it.
Here’s a simple example illustrating the theory of constructor parameters:
#include <iostream>
using namespace std;
// Define the Car class
class Car {
private:
string brand;
string model;
int year;
public:
// Constructor with parameters
Car(string b, string m, int y) {
brand = b;
model = m;
year = y;
}
// Method to display car information
void displayInfo() {
cout << "Brand: " << brand << ", Model: " << model << ", Year: " << year << endl;
}
};
int main() {
// Create objects of the Car class with different initialization options
Car car1("Toyota", "Camry", 2020);
Car car2("Honda", "Accord", 2021);
// Display car information
car1.displayInfo();
car2.displayInfo();
return 0;
}
Output:
Brand: Toyota, Model: Camry, Year: 2020
Brand: Honda, Model: Accord, Year: 2021