In object-oriented programming, a constructor is a special member function of a class that is used to initialize objects of that class. The constructor is automatically called when an object of the class is created, and it is used to set initial values for the object's data members.
A constructor has the same name as the class and no return type. It can have parameters or no parameters, depending on the needs of the class. The constructor can be used to allocate memory and initialize variables, among other tasks.
Constructors are useful in object-oriented programming because they provide a way to initialize objects when they are created, which helps ensure that the object is in a valid state from the beginning. They also allow objects to be created with different initial values, depending on the needs of the program.
In C++, if a class does not have a user-defined constructor, the compiler automatically provides a default constructor that has an empty body. However, if a class has one or more data members that need to be initialized to specific values, a user-defined constructor can be defined.
#include <iostream>
using namespace std;
class Cls{
public:
Cls() {
cout << "Automatic Loader" << endl;
}
};
int main() {
Cls Object;
return 0;
}
This code defines a class Cls
with a constructor that has no parameters. The constructor is defined with the same name as the class and is executed automatically when an object of the class is created.
In this case, the constructor simply outputs the message "Automatic Loader" to the console using the cout
statement.
The main
function creates an object of the Cls
class using the default constructor. This object is named Object
. Since the default constructor has no parameters, no arguments are needed in the constructor call.
When the program runs, the constructor is called automatically, and "Automatic Loader" is output to the console. The program then ends, since there is nothing else to execute.
#include <iostream>
using namespace std;
class Cls{
private:
string name;
string lastname;
int age;
public:
Cls() {
name = "Samantha";
lastname = "Fox";
age = 43;
cout << "Name: " << name << endl;
cout << "Lastname: " << lastname << endl;
cout << "Age: " << age << endl;
}
};
int main() {
Cls Object;
return 0;
}
This program defines a class Cls
with private data members name
, lastname
, and age
. It also defines a default constructor for the class Cls
.
The constructor initializes the private data members name
, lastname
, and age
with specific values for a person named Samantha Fox. Then it prints the values of these data members to the console.
In the main
function, an object of Cls
is created using the default constructor, and the object prints the values of the private data members to the console.
No comments:
Post a Comment