C++ Class Constructor with Parameters Example
In C++, a constructor is a special member function that is automatically called when an object of a class is created. It initializes the data members of the object. A constructor with parameters allows you to pass values to the object during its creation, providing flexibility and control over its initial state.
Here's a breakdown of how to use constructors with parameters:
Example: A Student Class
Let's define a simple Student
class with data members for name
, rollNumber
, and age
:
#include
#include
using namespace std;
class Student {
public:
// Constructor with parameters
Student(string name, int rollNumber, int age) {
this->name = name;
this->rollNumber = rollNumber;
this->age = age;
}
// Member function to display student details
void displayDetails() {
cout << "Name: " << name << endl;
cout << "Roll Number: " << rollNumber << endl;
cout << "Age: " << age << endl;
}
private:
string name;
int rollNumber;
int age;
};
Explanation:
-
Constructor declaration:
- The constructor
Student(string name, int rollNumber, int age)
takes three parameters:name
(a string),rollNumber
(an integer), andage
(an integer). - The constructor name is the same as the class name.
- It has no return type, not even
void
.
- The constructor
-
Initialization:
- Inside the constructor, we use
this->
to access the private data membersname
,rollNumber
, andage
of the object. - The constructor assigns the values of the parameters to the corresponding data members.
- Inside the constructor, we use
-
Member function
displayDetails()
:- This function prints the student's details to the console.
Creating and Using Objects
Now, let's create Student
objects and use the constructor to initialize them:
int main() {
// Creating objects with different values using the constructor
Student student1("Alice", 101, 18);
Student student2("Bob", 102, 19);
// Displaying details of each student
cout << "Student 1 details:\n";
student1.displayDetails();
cout << "\nStudent 2 details:\n";
student2.displayDetails();
return 0;
}
Output:
Student 1 details:
Name: Alice
Roll Number: 101
Age: 18
Student 2 details:
Name: Bob
Roll Number: 102
Age: 19
Key Points
- Constructors with parameters are essential for creating objects with specific initial values.
- The order of parameters in the constructor call must match the order of parameters in the constructor definition.
- You can have multiple constructors in a class, each with different parameters, allowing for different initialization scenarios.
- Constructors ensure that objects are created in a consistent and initialized state.
By using constructors with parameters, you enhance the flexibility and control over how your objects are created, promoting clean code and efficient initialization.