In C++, constructors are special member functions that are called when an object of a class is created. Constructors are used to initialize the data members of the object and perform any other necessary setup. Constructors have the same name as the class and no return type.
There are two types of constructors in C++: default constructors and parameterized constructors.
1. Default constructor: A default constructor is a constructor that takes no arguments. If a class does not define any constructors, the compiler automatically generates a default constructor. The default constructor initializes all data members to their default values. For example:
class Person { public: string name; int age; double height; Person() { name = ""; age = 0; height = 0.0; } };
In this example, a default constructor is defined for the `Person` class. The constructor initializes all data members to their default values.
2. Parameterized constructor: A parameterized constructor is a constructor that takes one or more arguments. The arguments are used to initialize the data members of the object. For example:
class Person { public: string name; int age; double height; Person(string n, int a, double h) { name = n; age = a; height = h; } };
In this example, a parameterized constructor is defined for the `Person` class. The constructor takes three arguments: astring `n`, an integer `a`, and a double `h`. These arguments are used to initialize the `name`, `age`, and `height` data members of the object.
When an object is created, the appropriate constructor is called automatically. If no arguments are provided, the default constructor is called. If arguments are provided, the parameterized constructor is called. For example:
Person p1; // calls default constructor Person p2("John Smith", 30, 1.8); // calls parameterized constructor
In this example, two objects of the `Person` class are created: `p1` and `p2`. The first object is created using the default constructor, which initializes all data members to their default values. The second object is created using the parameterized constructor, which initializes the `name`, `age`, and `height` data members to the values “John Smith”, 30, and 1.8, respectively.
Constructors can be used to initialize data members of an object and perform any other necessary setup. They provide a convenient way to ensure that objects are properly initialized when they are created, which can help prevent errors and make code easier to read and maintain.