A constructor in C++ is a special method that is automatically called when an object of a class is created. Constructors are used to initialize the data members of new objects.
Example
The following code shows a simple class named Person with a constructor:
class Person {
public:
Person(std::string name, int age) {
this->name = name;
this->age = age;
}
private:
std::string name;
int age;
};
The Person constructor has two parameters, name and age. When a new Person object is created, the constructor is automatically called and the name and age data members are initialized to the specified values.
Benefits of using constructors
There are several benefits to using constructors in C++, including:
Example
The following code shows how to use the Person constructor to create a new Person object:
Person person("John Doe", 30);
This code will create a new Person object with the name "John Doe" and the age 30.
Types of constructors
There are three types of constructors in C++:
Conclusion
Constructors are a powerful feature of C++ that can be used to write more robust and reliable code. By understanding how to use constructors, you can write better C++ code