Junior — Middle
Should you implement a constructor in a class and what is it used for?
sobes.tech AI
Answer from AI
A constructor in a class is used to initialize objects when they are created. It is automatically called when an instance of the class is created and allows setting initial values for the object's fields.
Implement a constructor if you need to ensure that the object will be created in a correct state, for example, with certain parameters or resources.
Example of a constructor in C++:
class Person {
public:
std::string name;
int age;
// Constructor
Person(const std::string& n, int a) : name(n), age(a) {}
};
int main() {
Person p("Ivan", 30); // calling the constructor
}
If a constructor is not explicitly defined, the compiler will create a default constructor that does not initialize the fields.