Chapter 9: Detailed Explanation of C++ Constructors and Destructors

Chapter 9: Detailed Explanation of C++ Constructors and Destructors

1 Overview

In C++, constructors and destructors are special member functions used to initialize objects and clean up object resources. The constructor is responsible for completing the initialization of the object, while the destructor is responsible for cleaning up resources at the end of the object's life cycle.

2. Constructor

A constructor is a special member function that has the same name as a class and has no return type. It is called automatically when an object is created to perform the necessary initialization operations.

2.1 Definition of constructor

Each class can have one or more constructors. According to the parameter list, constructors can be divided into parameterless constructors and parameterized constructors.

class MyClass {
    
    
public:
    // 无参构造函数
    MyClass() {
    
    
        // 初始化代码
    }

    // 有参构造函数
    MyClass(int value) {
    
    
        // 初始化代码
    }
};

2.2 Constructor call

The constructor is called automatically when the object is created, there is no need to explicitly call the constructor. When creating an object, the compiler will match the appropriate constructor to call based on the provided parameters.

MyClass obj1;           // 调用无参构造函数创建对象
MyClass obj2(100);      // 调用有参构造函数创建对象

2.3 Initialization List

The initialization list of the constructor can be used to initialize member variables. Using an initializer list provides a more efficient method of initialization and ensures that member variables are initialized in the correct order.

class MyClass {
    
    
private:
    int value;
    double scale;

public:
    MyClass(int v, double s) : value(v), scale(s) {
    
    
        // 初始化代码
    }
};

2.4 Default constructor

If no constructor is defined for a class, the compiler automatically generates a default constructor. The default constructor takes no parameters and does not perform any initialization. But once other constructors are customized, the compiler will no longer generate default constructors.

class MyClass {
    
    
public:
    // 自定义构造函数
    MyClass(int value) {
    
    
        // 初始化代码
    }

    // 编译器不会生成默认构造函数
};

2.5 copy constructor

A copy constructor is a special constructor used to create a new object and initialize it with an existing object. It can be called by value or by reference.

class MyClass {
    
    
public:
    // 拷贝构造函数
    MyClass(const MyClass& other) {
    
    
        // 初始化代码,使用other对象的值来初始化新的对象
    }
};

MyClass obj1;           // 调用无参构造函数创建对象obj1
MyClass obj2(obj1);     // 调用拷贝构造函数创建对象obj2,使用obj1的值来初始化

3. Destructor

A destructor is a special member function that has the same name as a class but preceded by a tilde (~). It is used to release resources occupied by objects.

3.1 Definition of destructor

Each class can only have one destructor, has no return type, and does not accept any parameters.

class MyClass {
    
    
public:
    // 析构函数
    ~MyClass() {
    
    
        // 清理资源的代码
    }
};

3.2 Destructor call

Destructors are called automatically when an object is destroyed and cannot be called explicitly manually. Destructors are called when an object goes out of scope, when the pointer to the object is deleted, or when the program ends.

void Function() {
    
    
    MyClass obj;    // 对象obj在该函数块结束时将被销毁,自动调用析构函数
}

int main() {
    
    
    MyClass* ptr = new MyClass();   // 使用new动态创建对象,需要手动delete释放内存
    delete ptr;                     // 调用析构函数后释放内存
    return 0;
}

3.3 Application of destructor

Destructors are often used to release resources occupied by objects, such as memory, file handles, network connections, and so on. Resource leaks can be avoided by performing necessary cleanup operations in the destructor.

class FileManager {
    
    
private:
    FILE* file;

public:
    FileManager(const char* filename) {
    
    
        file = fopen(filename, "r");   // 打开文件
        if (!file) {
    
    
            // 处理打开文件失败的情况
        }
    }

    ~FileManager() {
    
    
        if (file) {
    
    
            fclose(file);   // 关闭文件
        }
    }
};

4. Example Case: Library Management System

Below is a simple library management system example to show the constructor and destructor in action.

#include <iostream>
#include <vector>

using namespace std;

// Book类表示图书对象
class Book {
    
    
private:
    string title;
    string author;

public:
    Book(const string& t, const string& a) : title(t), author(a) {
    
    
        cout << "Book \"" << title << "\" by " << author << " created." << endl;
    }

    ~Book() {
    
    
        cout << "Book \"" << title << "\" by " << author << " destroyed." << endl;
    }

    void display() {
    
    
        cout << "Title: " << title << endl;
        cout << "Author: " << author << endl;
    }
};

// Library类表示图书馆
class Library {
    
    
private:
    vector<Book> books;

public:
    void addBook(const Book& book) {
    
    
        books.push_back(book);
    }

    void displayAllBooks() {
    
    
        for (const auto& book : books) {
    
    
            book.display();
            cout << endl;
        }
    }
};

int main() {
    
    
    Library library;
    library.addBook(Book("Harry Potter", "J.K. Rowling"));
    library.addBook(Book("To Kill a Mockingbird", "Harper Lee"));
    library.displayAllBooks();

    return 0;
}

operation result:

Book "Harry Potter" by J.K. Rowling created.
Book "To Kill a Mockingbird" by Harper Lee created.
Title: Harry Potter
Author: J.K. Rowling

Title: To Kill a Mockingbird
Author: Harper Lee

Book "Harry Potter" by J.K. Rowling destroyed.
Book "To Kill a Mockingbird" by Harper Lee destroyed.

Running the above sample code, we can see the calling of the constructor and destructor. When creating a book object, the constructor is called, the member variables of the object are initialized, and the corresponding prompt information is output. And when the program ends, or when the book object is deleted from the library, the destructor will be called, the resources occupied by the object will be released, and the corresponding destruction information will be output.

Guess you like

Origin blog.csdn.net/qq_51447496/article/details/132241628