Constructors
in C++ are special member functions within a class that are automatically invoked when an object of that class is created. Constructors initialize the object's data members, set up the object's state, and perform any necessary setup tasks. They have the same name as the class and do not have a return type.
Types of Constructors in C++:
Default Constructor:
A constructor with no parameters is called a default constructor.
It is automatically invoked when an object is created without specifying any values
class
MyClass
{
public:
MyClass
() {
}
};
Parameterized Constructor:
A constructor with parameters is called a parameterized constructor.
It allows you to initialize the object with specific values at the time of creation.
class
Car
{
private:
string
brand;
int
year;
public:
Car
(
string
brand
,
int
year
) {
this
->
brand
=
brand;
this
year
=
year;
}
};
Copy Constructor:
A copy constructor creates a new object as a copy of an existing object.
It is called when an object is passed by value or when an object is explicitly created as a copy of another object.
class
Person
{
private:
string
name;
int
age;
public:
Person
(
const
Person
&
other
) {
this
->
name
=
other
.
name
;
this
age
=
other
.
age
;
}
};
Initializer List:
In C++, constructors can use an initializer list to initialize data members, providing a more efficient way to initialize member variables.
class
Rectangle
{
private:
int
length;
int
width;
public:
Rectangle
(
int
len
,
int
wid
) :
length
(
len
),
width
(
wid
) {
}
};
Understanding constructors is
crucial
for effective object
initialization
and proper resource management in C++
programs
.
Constructors
help ensure that objects are in a valid and consistent state when they are created.