๐งฑ Introduction to Constructors
A constructor is a special member function of a class that is automatically called when an object is created.
Its main purpose is to initialize objects.
โ Key Features of Constructors
- Same name as the class name.
- No return type, not even
void
. - Automatically invoked when an object is created.
- Can be overloaded (multiple constructors with different parameters).
๐งช Example:
#include <iostream>
using namespace std;
class Student {
public:
int rollNo;
// Constructor
Student() {
rollNo = 101;
cout << "Constructor called!" << endl;
}
void display() {
cout << "Roll No: " << rollNo << endl;
}
};
int main() {
Student s1; // Constructor is called automatically
s1.display();
return 0;
}
๐ Output:
Constructor called!
Roll No: 101
๐ท Types of Constructors
Type | Description |
---|---|
Default Constructor | Takes no parameters. |
Parameterized Constructor | Takes arguments to initialize data. |
Copy Constructor | Creates a copy of another object. |
1. Default Constructor
cppCopyEditclass A {
public:
A() {
cout << "Default constructor called!" << endl;
}
};
2. Parameterized Constructor
class Student {
public:
int roll;
Student(int r) { // Constructor with parameter
roll = r;
}
void display() {
cout << "Roll No: " << roll << endl;
}
};
3. Copy Constructor
class Student {
public:
int roll;
Student(int r) {
roll = r;
}
// Copy constructor
Student(const Student &s) {
roll = s.roll;
}
void display() {
cout << "Roll: " << roll << endl;
}
};
๐ Why Use Constructors?
- Ensures automatic initialization of objects.
- Helps avoid writing extra code to initialize variables.
- Makes code cleaner and safer.
๐ Constructor vs. Member Function
Feature | Constructor | Member Function |
---|---|---|
Name | Same as class | Any valid identifier |
Return Type | No return type | Can have return type |
Call Time | Called automatically | Called manually |
Purpose | Initialization | Perform specific task |
๐ง Real-Life Analogy
Think of a constructor like the initial setup process when you open a new smartphone:
- Language, time zone, and Wi-Fi setup.
- It happens automatically, once.
- After setup, you can manually use different apps (like member functions).
๐งพ Summary
- A constructor initializes class objects.
- It runs automatically when an object is created.
- There are three main types: default, parameterized, and copy constructors.
- Constructors help make code modular, reusable, and clean.