C++ Class Constructors & Destructors
Class constructor
The class'sconstructoris a special member function of the class that is executed automatically each time a new object of the class is created.
A constructor has exactly the same name as the class and has no return type (not even void void). Constructors are typically used to set initial values for member variables.
If no constructor is explicitly defined, the compiler automatically generates a default constructor that does nothing.
The example below helps to better understand the concept of constructors:
Example
#include
<
iostream
using
namespace
std;
class
Line
{
public
:
Line
(
)
;
// Constructor declaration
void
setLength
(
double
len
)
;
double
getLength
(
)
const
;
private
:
double
length
;
}
;
// Constructor definition
Line
::
Line
(
)
{
cout
<<
"
Object is being created
"
<<
endl
;
length
=
0
.0
;
// Explicitly initialize member variables
}
void
Line
::
setLength
(
double
len
)
{
length
=
len
;
}
double
Line
::
getLength
(
)
const
{
return
length
;
}
// main function of the program
int
main
(
)
{
Line
line
;
// Set length
line
.
setLength
(
6
.0
)
;
cout
<<
"
Length of line :
"
<<
line
.
getLength
(
)
<<
endl
;
return
0
;
}
When the code above is compiled and executed, it produces the following result:
Object is being created
Length of line : 6
Parameterized Constructors
The default constructor takes no parameters, but if needed, a constructor can also take parameters. This assigns initial values to the object at creation time, without separately calling set a function, as shown in the example below:
Example
#include
<
iostream
using
namespace
std;
class
Line
{
public
:
Line
(
double
len
)
;
// Parameterized constructor declaration
void
setLength
(
double
len
)
;
double
getLength
(
)
const
;
private
:
double
length
;
}
;
// Constructor definition
Line
::
Line
(
double
len
)
{
cout
<<
"
Object is being created, length =
"
<<
len
<<
endl
;
length
=
len
;
}
void
Line
::
setLength
(
double
len
)
{
length
=
len
;
}
double
Line
::
getLength
(
)
const
{
return
length
;
}
// main function of the program
int
main
(
)
{
Line
line
(
10
.0
)
;
// Pass the initial length directly when creating the object
// Get the initial length
cout
<<
"
Length of line :
"
<<
line
.
getLength
(
)
<<
endl
;
// Reset the length
line
.
setLength
(
6
.0
)
;
cout
<<
"
Length of line :
"
<<
line
.
getLength
(
)
<<
endl
;
return
0
;
}
When the code above is compiled and executed, it produces the following result:
Object is being created, length = 10
Length of line : 10
Length of line : 6
Using Initialization Lists to Initialize Fields
C++ recommends using themember initialization listto initialize member variables. Its syntax places a colon after the constructor parameter list (:), then writes 成员变量名(初始值).
In the following example,: length(len) means: use the passed-in parameter len to directly initialize the member variable length. Note that cout prints the member variable length, not the parameter len, so you can intuitively verify the member variable was assigned correctly:
Line
::
Line
(
double
len
)
:
length
(
len
)
{
// At this point length is already assigned via the initialization list; print length to verify the result
cout
<<
"
Object is being created, length =
"
<<
length
<<
endl
;
}
The syntax above is equivalent to the following in-function-body assignment; both produce exactly the same output:
Line
::
Line
(
double
len
)
{
length
=
len
;
// Assign parameter len to member variable length
cout
<<
"
Object is being created, length =
"
<<
length
<<
endl
;
}
The difference between the two approaches is: the initialization list completes member initialization before entering the function body,whereas in-function-body assignment first default-constructs then assigns, adding an extra step. For const const members, reference members, and object members without a default constructor, the initialization list isthe onlyway to initialize them.
Suppose a class C has multiple fields X, Y, Z, etc. that need initialization; simply separate them with commas, as shown below:
C
::
C
(
double
a
,
double
b
,
double
c
)
:
X
(
a
)
,
Y
(
b
)
,
Z
(
c
)
{
// Other initialization logic (if any)
}
Note:The initialization order of members in the initialization list is determined by theirdeclaration orderin the class, not the written order; it is recommended to keep them consistent to avoid confusion.
Class Destructor
The class'sThe destructoris a special member function of the class that is executed automatically when an object's lifetime ends (when it leaves scope or is delete), used to release the resources held by the object (such as dynamic memory, file handles, etc.).
A destructor has exactly the same name as the class, except with a tilde (~) prefixed. It returns no value and takes no parameters; each class can have only one destructor.
The example below helps to better understand the concept of destructors:
Example
#include
<
iostream
using
namespace
std;
class
Line
{
public
:
Line
(
)
;
// Constructor declaration
~
Line
(
)
;
// Destructor declaration
void
setLength
(
double
len
)
;
double
getLength
(
)
const
;
private
:
double
length
;
}
;
// Constructor definition
Line
::
Line
(
)
{
cout
<<
"
Object is being created
"
<<
endl
;
length
=
0
.0
;
}
// Destructor definition
Line
::~
Line
(
)
{
cout
<<
"
Object is being deleted
"
<<
endl
;
// If there are dynamically allocated resources, release them here, e.g.: delete[] data;
}
void
Line
::
setLength
(
double
len
)
{
length
=
len
;
}
double
Line
::
getLength
(
)
const
{
return
length
;
}
// main function of the program
int
main
(
)
{
Line
line
;
// When the program ends, the destructor is called automatically
// Set length
line
.
setLength
(
6
.0
)
;
cout
<<
"
Length of line :
"
<<
line
.
getLength
(
)
<<
endl
;
return
0
;
}
When the code above is compiled and executed, it produces the following result:
Object is being created
Length of line : 6
Object is being deleted
C++ Classes & Objects