Constructor and destructor for C++ learning

foreword

In general, the constructor is responsible for the initialization of the object, and the destructor is responsible for the cleanup of the object and the release of resources. They are very important concepts in C++ object-oriented programming. They are used to manage the life cycle of objects and ensure that objects can be properly initialized and cleaned up when they are created and destroyed.

text

insert image description here

look at the code

class person
{
public:
	person(){
		cout << " 这是一个构造函数 " << endl;
	}

	~person()
	{
		cout << " 这是一个析构函数 " << endl;
	}
};

int main()
{
	person mike;
	system("pause"); 
	return 0;
}

This C++ code defines a class named person, and creates an object mike of the person class in the main function. Let's step through this code to understand what the constructor and destructor do:

class person
{
public:
    person(){
        cout << " 这是一个构造函数 " << endl;
    }

    ~person()
    {
        cout << " 这是一个析构函数 " << endl;
    }
};

Here a class named person is defined. There are two special member functions in this class: constructor and destructor.

Constructor: A constructor has the same name as the class name and has no return type (including void). In this constructor, there is only one line of code, which outputs "this is a constructor".

Destructor: A destructor has the same name as the class name, preceded by a tilde (~), and also has no return type. In this destructor, there is only one line of code, which outputs "this is a destructor".

main function:

int main()
{
    person mike;
    system("pause"); 
    return 0;
}

In the main function, an object mike of the person class is first created. When the object mike is created, the constructor is automatically called, thus outputting "this is a constructor".

Then, the program executes system("pause") to wait for the user to press any key to continue, preventing the console window from closing immediately.

Finally, the main function ends and the program returns 0. At the end of the main function, the object mike goes out of scope, so the destructor is called automatically, outputting "this is a destructor".

Summarize:

  • Constructors are used to initialize objects and are usually called automatically when an object is created.
  • Destructors are used to clean up objects and are usually called automatically when an object goes out of scope or is explicitly deleted.

In this example, the main role of the constructor and destructor is to perform specific actions at the beginning and end of the object's lifetime.

Guess you like

Origin blog.csdn.net/wniuniu_/article/details/132635087