What is constructor ? Explain different types of constructor
In : BCA Subject : OOPS and Data StructuresA constructor is a special member function of a class that is automatically called when an object of the class is created .
Key Point : Same as the class name , No return type , Called Automatically when object created.
## Different Types of Constructors
There are three main types of constructors in C++:
# Default Constructor
- A constructor that takes **no arguments**
- If you don’t define any constructor, the compiler creates one by default
Example:
class Student {
public:
Student() {
cout << "Default constructor called!" << endl;
}
};
Student s1; // Default constructor is called
# Parameterized Constructor
- A constructor that takes **one or more arguments**
- Used to initialize objects with specific values
Example:
class Student {
private:
string name;
int age;
public:
// Parameterized constructor
Student(string n, int a) {
name = n;
age = a;
}
void display() {
cout << "Name: " << name << ", Age: " << age << endl;
}
};
Student s2("Alice", 20);
s2.display(); // Output: Name: Alice, Age: 20
# Copy Constructor
- A constructor that initializes an object using **another object of the same class**
- It copies values from one object to another
Example:
class Student {
private:
string name;
int age;
public:
Student(string n, int a) {
name = n;
age = a;
}
// Copy constructor
Student(const Student &obj) {
name = obj.name;
age = obj.age;
}
void display() {
cout << "Name: " << name << ", Age: " << age << endl;
}
};
Student s1("Bob", 22);
Student s2 = s1; // Copy constructor is called
s2.display(); // Output: Name: Bob, Age: 22