C++ Class Constructor & Destructor

C++ Classes & Objects

Class constructor

ClassConstructorA constructor is a special member function of a class, automatically executed every time a new object of the class is created.

The constructor's name is exactly the same as the name of the class, and it has no return type (not evenvoidmeans that b is an object array of class AB, containing 3 objects; therefore, the constructor is called 3 times;

means that p is an object pointer array of class AB, containing 4 class object pointers; no constructor is called.

The following example 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; } // The 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 above code is compiled and executed, it produces the following results:

Object is being created
Length of line : 6

Parameterized constructors

The default constructor has no parameters, but if needed, constructors can also have parameters. In this way, initial values are assigned to the object when it is created, with no need for a separate callsetfunctions, as shown in the following example:

Example

#include <iostream> using namespace std; class Line { public: Line(double len); // Constructor declaration with parameters 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; } // The main function of the program int main() { Line line(10.0); // Pass initial length directly when creating an object // Get the initial length cout << "Length of line : " << line.getLength() << endl; // Reset length line.setLength(6.0); cout << "Length of line : " << line.getLength() << endl; return 0; }

When the above code is compiled and executed, it produces the following results:

Object is being created, length = 10
Length of line : 10
Length of line : 6

Using initializer lists to initialize fields

C++ recommends usingMember initializer listto initialize the member variables. Its syntax is to add a colon after the constructor's parameter list,:), then writemember variable name (initial value)。

In the following example,: length(len)means: using the passed-in parameterlento directly initialize member variableslength. NotecoutWhat is printed is the member variablelength, rather than a parameterlenallowing you to intuitively verify that the member variables have been correctly assigned:

Line::Line(double len) : length(len) { // At this point, length has been assigned via the initialization list; print length to verify the result cout << "Object is being created, length = " << length << endl; }

The above syntax is equivalent to the following assignment in the function body; the two 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 that the initialization list completes the initialization of the member variables before entering the function body,beforewhile assignment inside the function body first default-constructs and then assigns, which is one extra step. Forconstconst members, reference members, and object members without a default constructor, the initialization list isuniquethe initialization method.

Suppose there is a class C with multiple fields X, Y, Z, etc. that need to be initialized; simply separate the different fields 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 their order in the class,declaration ordernot by the order in which they are written. It is recommended to keep them consistent to avoid confusion.

Class destructor

ClassdestructorA destructor is a special member function of a class. At the end of an object's lifetime (when it goes out of scope or isdeletedeleted), it is automatically executed to release the resources occupied by the object (such as dynamic memory, file handles, etc.).

The name of the destructor is exactly the same as the name of the class, except that a tilde (~) is added before it~as a prefix. It does not return any value, cannot have any parameters, and each class can have only one destructor.

The following example 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; } // The 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 above code is compiled and executed, it produces the following results:

Object is being created
Length of line : 6
Object is being deleted

C++ Classes & Objects

other extensions