What is Parameterized Constructor in C++: Simple Explanation and Example
parameterized constructor in C++ is a special function inside a class that allows you to create objects with initial values by passing arguments. It helps set up an object’s properties right when it is created, making your code cleaner and more flexible.How It Works
Think of a parameterized constructor like a recipe that needs ingredients to make a dish. When you create an object, you give it specific values (ingredients) that the constructor uses to set up the object’s properties (the dish). This means you don’t have to set each property one by one after creating the object.
In C++, a constructor is a special function with the same name as the class. A parameterized constructor takes one or more inputs (parameters) to initialize the object. This is useful because it lets you create many objects with different starting values easily, just by passing different arguments.
Example
This example shows a class Car with a parameterized constructor that sets the car's brand and year when creating an object.
#include <iostream> #include <string> class Car { public: std::string brand; int year; // Parameterized constructor Car(std::string b, int y) { brand = b; year = y; } void display() { std::cout << "Brand: " << brand << ", Year: " << year << std::endl; } }; int main() { Car car1("Toyota", 2020); Car car2("Honda", 2018); car1.display(); car2.display(); return 0; }
When to Use
Use a parameterized constructor when you want to create objects that start with specific values right away. This is helpful in real-world cases like setting up a user profile with a name and age, creating a product with a price and ID, or initializing a game character with health and strength.
It saves time and reduces errors because you don’t have to remember to set each property after creating the object. Instead, you provide all needed information upfront, making your code easier to read and maintain.
Key Points
- A parameterized constructor takes arguments to initialize an object’s properties.
- It has the same name as the class and no return type.
- It helps create objects with different initial values easily.
- If you define a parameterized constructor, the default constructor is not created automatically.