In C++, a constructors is a special member function of a class that is called automatically when an object of the class is created. The constructor is used to initialize the data members of the object to some default or specified values.
The constructor has the same name as the class and does not have a return type. It can have parameters, which are used to pass arguments to the constructor when the object is created.
Here’s an example of a class with a constructor:
class Person {
public:
std::string name;
int age;
Person(std::string n, int a) {
name = n;
age = a; }};
In this example, the Person class has two data members (name and age) and a constructor that takes two parameters (n and a). Inside the constructor, the values of n and a are assigned to the name and age data members, respectively.
To create an object of the Person class, you would call the constructor with the desired arguments:
Person john("John", 30);
This creates an object of type Person called john with the name “John” and age 30. The constructor is called automatically when the object is created.
It is possible to define multiple constructors for a class, each with a different set of parameters. This is called constructor overloading. For example:
class Person {
public:
std::string name;
int age;
Person() {
name = "Unknown";
age = 0;
}
Person(std::string n, int a) {
name = n;
age = a;
} };
In this example, the Person class has two constructors – one with no parameters (which initializes name to “Unknown” and age to 0) and one with two parameters (which initializes name and age to the specified values).
When an object of the Person class is created, the appropriate constructor is called based on the number and types of arguments provided:
Person unknown; // calls the default constructor
Person jane("Jane", 25); // calls the parameterized constructor
Type of constructor:
There are several types of constructors that can be used to create objects of a class:
Example:
class Person {
public:
Person() {
name = "John Doe";
age = 30;
}
private:
string name;
int age; };
Example:
class Person {
public:
Person(string n, int a) {
name = n;
age = a;
}
private:
string name;
int age;
};
Example:
class Person {
public:
Person(const Person& other) {
name = other.name;
age = other.age;
}
private:
string name;
int age; };
Note that a class can have multiple constructors with different parameter lists, and the appropriate constructor is called based on the arguments provided when an object is created. Additionally, a constructor can be overloaded to provide different behavior for different arguments.
Learners TV is a website that is designed to educate users and provide instructional material on particular subjects and topics.