C++ constructors
Created By: chatGPT
In C++, constructors are special member functions that are automatically invoked when an object of a class is created. They are used to initialize an object's attributes and allocate resources as necessary. Constructors have the same name as the class and do not have a return type.
class MyClass {
public:
MyClass() {
// Default constructor
std::cout << "Object created!" << std::endl;
}
};
You can also define parameterized constructors that take arguments to initialize an object with specific values. This allows for greater flexibility in object creation.
class MyClass {
private:
int value;
public:
MyClass(int v) {
value = v;
std::cout << "Object created with value: " << value << std::endl;
}
};
It's also possible to have multiple constructors in a class, making use of constructor overloading. This means that you can define multiple constructors with different signatures.
class MyClass {
public:
MyClass() {
std::cout << "Default constructor called" << std::endl;
}
MyClass(int v) {
std::cout << "Parameterized constructor called with: " << v << std::endl;
}
};
In cases where you need to copy an object, you can define a copy constructor. The copy constructor creates a new object as a copy of an existing object.
class MyClass {
private:
int value;
public:
MyClass(int v) : value(v) {}
MyClass(const MyClass &obj) {
value = obj.value;
std::cout << "Copy constructor called" << std::endl;
}
};
Lastly, destructors are used to free resources when an object goes out of scope. A destructor has the same name as the class but is preceded by a tilde (~) and does not take any parameters.
class MyClass {
public:
MyClass() {
std::cout << "Object created!" << std::endl;
}
~MyClass() {
std::cout << "Object destroyed!" << std::endl;
}
};