There are three types of constructors in C++: default constructor, parameterized constructor, and copy constructor.
- Default Constructor: It is a constructor that takes no arguments. If a class does not have any constructors defined, the compiler generates a default constructor automatically.
Example code:
class MyClass {
public:
// Default constructor
MyClass() {
// Initialization code
// ...
}
};
- Parameterized Constructor: It is a constructor that takes one or more parameters. It allows you to initialize the object with specific values.
Example code:
class MyClass {
public:
// Parameterized constructor
MyClass(int value) {
// Initialization code
// ...
}
};
int main() {
// Creating an object of MyClass with a parameter
MyClass obj(10);
// ...
return 0;
}
- Copy Constructor: It is a constructor that creates a new object by copying the values from an existing object of the same class.
Example code:
class MyClass {
public:
// Copy constructor
MyClass(const MyClass& other) {
// Copy the values from 'other' to the new object
// ...
}
};
int main() {
// Creating an object of MyClass and initializing it with another object
MyClass obj1;
MyClass obj2(obj1); // Copy constructor called
// ...
return 0;
}