In C++, constructors are special member functions that initialize objects of a class. They have the same name as the class and do not return any value.
A constructor that takes no parameters. It initializes objects with default values.
class MyClass {
public:
int x;
// Default constructor
MyClass() {
x = 0;
}
};
A constructor that takes arguments to initialize an object with specific values.
class MyClass {
public:
int x;
// Parameterized constructor
MyClass(int val) {
x = val;
}
};
A constructor that initializes an object using another object of the same class. It is called when:
class MyClass {
public:
int x;
// Copy constructor
MyClass(const MyClass &obj) {
x = obj.x;
}
};
Introduced in C++11, it transfers resources from a temporary object (rvalue) to a new object, improving performance by avoiding unnecessary copies.
class MyClass {
public:
int* data;
// Move constructor
MyClass(MyClass &&obj) noexcept {
data = obj.data;
obj.data = nullptr;
}
};
Introduced in C++11, it allows one constructor to call another constructor in the same class, reducing code duplication.
class MyClass {
public:
int x;
int y;
// Delegating constructor
MyClass() : MyClass(0, 0) {}
MyClass(int a, int b) {
x = a;
y = b;
}
};
You can have multiple constructors in a class, each with different parameters.
class MyClass {
public:
int x;
int y;
MyClass() {
x = 0;
y = 0;
}
MyClass(int a) {
x = a;
y = 0;
}
MyClass(int a, int b) {
x = a;
y = b;
}
};
#include <iostream>
class Car {
public:
std::string brand;
int year;
// Default constructor
Car() : brand("Unknown"), year(0) {}
// Parameterized constructor
Car(std::string b, int y) : brand(b), year(y) {}
// Copy constructor
Car(const Car &c) : brand(c.brand), year(c.year) {}
void display() {
std::cout << "Brand: " << brand << ", Year: " << year << std::endl;
}
};
int main() {
Car car1; // Default constructor
Car car2("Toyota", 2020); // Parameterized constructor
Car car3(car2); // Copy constructor
car1.display();
car2.display();
car3.display();
return 0;
}