In depth analysis of constructors and destructors in C++
- 2020-04-02 01:24:48
- OfStack
Constructor:
This is done automatically when a class instantiates an object, initializing the data in the class. Constructors can be from load, there can be more than one, but only one default constructor.
Destructor:
A function that does something before revoking the memory held by an object. Destructors cannot be overridden, there can only be one.
The sequence of constructor and destructor calls:
Post-destructor constructed first and post-conformation folded first. It's like a stack, first in, then out.
#include<iostream>
#include<string>
using namespace std;
class Student{
public:
Student(string,string,string);
~Student();
void show();
private:
string num;
string name;
string sex;
};
Student::Student(string nu,string na,string s){
num=nu;
name=na;
sex=s;
cout<<name<<" is builded!"<<endl;
}
void Student::show(){
cout<<num<<"t"<<name<<"t"<<sex<<endl;
}
Student::~Student(){
cout<<name<<" is destoried!"<<endl;
}
int main(){
Student s1("001"," thousand "," male ");
s1.show();
Student s2("007"," Steel hand "," female ");
s2.show();
cout<<"nihao"<<endl;
cout<<endl;
cout<<"NIHAO"<<endl;
return 0;
}
< img Alt = "" border = 0 SRC =" / / files.jb51.net/file_images/article/201309/20130903080000.png ">
A thousand hands constructed first and a thousand hands resulting in subsequent destruction; After the construction of the class hand, the result of the first folded class hand.
Features:
The destructor is called only when the main function ends or the exit function ends the program.
If the object is defined in a function, its constructor is called when the object is created, and the destructor is called first when the function call ends and the object is released.
#include<iostream>
#include<string>
using namespace std;
class Student{
public:
Student(string,string);
~Student();
void show();
string num;
string name;
};
Student::Student(string nu,string na){
num=nu;
name=na;
cout<<name<<" is builded!"<<endl<<endl;
}
void Student::show(){
cout<<num<<"t"<<name<<endl<<endl;
}
Student::~Student(){
cout<<name<<" is destoried!"<<endl<<endl;
}
void fun(){
cout<<"============ call fun function ============"<<endl<<endl;
Student s2("002"," Automatic local variable ");//Define an automatic local object
s2.show();
static Student s3("003"," Static local variable ");//Define static local variables
s3.show();
cout<<"===========fun End of function call =============="<<endl<<endl;
}
int main(){
Student s1("001"," The global variable ");
s1.show();
fun();
cout<<"nthis is some content before the endn";//This is a section before the main function ends and after the function is called
cout<<endl;
return 0;
}
< img Alt = "" border = 0 SRC =" / / files.jb51.net/file_images/article/201309/20130903080209.png ">