Introduction
In C++, constructors are special functions that allow for efficient and controlled initialization of objects. They provide a way to assign initial values when an object is created, making them a crucial part of object-oriented programming.
What is a Constructor in C++?
A constructor is a unique member function automatically called when an object of a class is created. It has the same name as the class and doesnβt return a value. Constructors are essential for setting up initial values or allocating resources at the time of object creation.
Types of Constructors in C++
Default Constructor
A default constructor is one that takes no arguments. If no constructor is defined, C++ automatically provides a default constructor. If we make another constructor then default constructor is automatically removed and if we want to use the functionalities of default constructor then we have to make a new default constructor. Below is the code of default constructor in C++
class Car {
public:
int speed;
// Default constructor
Car() {
speed = 0;
std::cout << "Default constructor called, speed set to 0." << std::endl;
}
};
int main() {
Car myCar; // Default constructor called
}
Parameterized Constructor
A parameterized constructor allows passing values to initialize an object. A class can have multiple parameterized constructors but with different parameters and if are passing the same parameters than the order of that parameters should be different. Below is the code of parameterized constructor.
class Car {
public:
int speed;
// Parameterized constructor
Car(int s) {
speed = s;
std::cout << "Parameterized constructor called, speed set to " << speed << "." << std::endl;
}
};
int main() {
Car myCar(100); // Parameterized constructor called
}
Copy Constructor
The copy constructor initializes a new object as a copy of an existing object. In this, we pass object as the parameter to the constructor. Below is the code of copy constructor in C++.
class Car {
public:
int speed;
// Copy constructor
Car(const Car &c) {
speed = c.speed;
std::cout << "Copy constructor called, speed copied: " << speed << "." << std::endl;
}
};
int main() {
Car myCar(120);
Car anotherCar = myCar; // Copy constructor called
}
Conclusion
Constructors are the backbone of C++ class initialization, providing flexible ways to create and configure objects. By understanding the types of constructors and best practices, you can write more efficient and robust code in C++.
Top comments (0)