Metadata
- 📅 Date :: 23-04-2025
- 🏷️ Tags :: cpp
Notes
Detailed Notes on Constructors in C++
What is a Constructor?
A constructor is a special type of method in a class that is automatically called when an object is instantiated (created). The constructor is useful for initializing the attributes (data members) of an object when it is created, allowing you to assign values to them before you start using the object.
Constructors are invoked automatically when you create an object. However, they can also be explicitly defined to customize how the object’s attributes should be initialized.
Key Characteristics of a Constructor:
- Same Name as the Class: The constructor must have the same name as the class it belongs to. For example, in a
Studentclass, the constructor is namedStudent. - No Return Type: Constructors do not have a return type, not even
void. - Called Automatically: When an object of the class is created, the constructor is invoked automatically, initializing the object’s attributes with given values.
- Parameters: Constructors can accept parameters, which are used to initialize an object’s attributes when it is created.
- Used for Initialization: The main purpose of the constructor is to assign initial values to the attributes of an object.
Creating a Constructor: Example with Student Class
Let’s walk through an example of using a constructor with a Student class.
Step 1: Define the Student Class
First, define the Student class with some attributes like name, age, and GPA.
class Student {
public:
string name;
int age;
double gpa;
};
Step 2: Define the Constructor
Next, create the constructor for the Student class. The constructor will have the same name as the class and will accept parameters to initialize the attributes:
Student(string n, int a, double g) {
name = n;
age = a;
gpa = g;
}
Here, Student(string n, int a, double g) is the constructor. The parameters n, a, and g are used to assign values to the name, age, and gpa attributes of the object.
Step 3: Create and Initialize Objects
When creating an object of the Student class, the constructor is automatically called with the values passed as arguments. Here’s how you would instantiate the Student object:
Student student1("Spongebob", 25, 3.2);
This creates a Student object named student1 and assigns the values "Spongebob", 25, and 3.2 to the name, age, and gpa attributes respectively.
Step 4: Display Attributes
You can now display the attributes of student1 to check that the constructor has properly initialized the values:
cout << student1.name << endl; // Output: Spongebob
cout << student1.age << endl; // Output: 25
cout << student1.gpa << endl; // Output: 3.2
Constructor Using this Keyword
If the constructor’s parameter names are the same as the attribute names, you need to use the this keyword to differentiate between the attribute and parameter. For example:
Student(string name, int age, double gpa) {
this->name = name;
this->age = age;
this->gpa = gpa;
}
Here, this->name refers to the object’s attribute, while name refers to the parameter passed to the constructor.
Alternatively, if you use different names for the parameters, you can assign values directly without needing the this keyword. For example:
Student(string x, int y, double z) {
name = x;
age = y;
gpa = z;
}
Multiple Objects with Constructors
You can create multiple objects of the same class, and each one can be initialized using the constructor with different values:
Student student2("Patrick", 40, 1.5);
Student student3("Sandy", 21, 4.0);
You can then display each student’s attributes:
cout << student2.name << " " << student2.age << " " << student2.gpa << endl;
cout << student3.name << " " << student3.age << " " << student3.gpa << endl;
Output:
Patrick 40 1.5
Sandy 21 4.0
Constructor in the Car Class: Example
Now, let’s look at an example where we use a constructor to initialize the attributes of a Car object.
Step 1: Define the Car Class
The Car class will have attributes like make, model, year, and color:
class Car {
public:
string make;
string model;
int year;
string color;
};
Step 2: Define the Constructor
We’ll define a constructor for the Car class that initializes these attributes:
Car(string make, string model, int year, string color) {
this->make = make;
this->model = model;
this->year = year;
this->color = color;
}
Step 3: Create and Initialize Car Objects
Now, you can create Car objects and initialize their attributes:
Car car1("Chevy", "Corvette", 2022, "Blue");
Car car2("Ford", "Mustang", 2023, "Red");
Step 4: Display Car Attributes
You can print the attributes of each car object to check the initialization:
cout << car1.make << " " << car1.model << " " << car1.year << " " << car1.color << endl;
cout << car2.make << " " << car2.model << " " << car2.year << " " << car2.color << endl;
Output:
Chevy Corvette 2022 Blue
Ford Mustang 2023 Red
Conclusion
- Constructors are special methods in C++ classes that initialize objects when they are created.
- Constructors automatically set initial values for the attributes of the object.
- They can be defined with or without parameters, and they can be called with arguments to initialize the attributes.
- Using constructors improves code readability, simplifies object initialization, and avoids manual assignment of values to attributes after object creation.