C++-constructor, destructor and copy constructor

One, the constructor

In the process of program execution, when encountering the statement statement, the program will apply to the operating system for a certain amount of memory space for storing the newly created object. But compared with ordinary variables, the object of the class is particularly complicated, and the compiler does not know how to generate code to initialize the object, which leads to the constructor.

1.1 What is a constructor?

In C++, the constructor is a special member function, and the compiler will call the constructor by default for initialization every time a class is created.

1.2 Why is there a constructor?

The role of the constructor is to construct the object with a specific value when the object is created, and initialize the object to a specific state.

1.3 How to use the constructor?

To learn how to use a constructor, you first need to understand some special properties of the constructor: the function name of the constructor is the same as the class name, and there is no return value; the constructor is usually declared as a public function.

Notes: As long as there is a constructor in the class, the compiler will automatically insert the code that calls the constructor in the place where a new object is created. So the constructor will be called automatically when the object is created.

Several common constructors are introduced below:

  1. Default constructor:
class Clock
{
    
    
public:
    Clock()   //编译器自动生成的隐含的默认构造函数;
    {
    
    
        
    }
    ....
};

There is no need to provide parameters when the default constructor is called. If a constructor is not written in the class, the compiler will automatically generate an implicit default constructor parameter. The parameter list and function body of the constructor are empty, and the constructor does nothing.

Notes: Both the parameterless constructor and the full default constructor are called default constructors.

Q: Since the default constructor does not do anything, why do you want to generate this constructor?

Answer: Because C++ must do something when the constructor is automatically called when the object is created. In the above example, the default constructor does nothing, but some constructors with empty function bodies do not do nothing, because it is also responsible for the construction of the base class and the construction of member objects.

  1. Parameter constructor and parameterless constructor
class Clock
{
    
    
public:
    Clock(int NewH,int NewM,int NewS);  //有参数的构造函数
    Clock()   //无参数的构造函数
    {
    
    
        hour = 0;
        minute = 0;
        second = 0;
    }
    void SetTime(int NewH,int NewM,int NewS);
    void ShowTime();

private:
    int hour,minute,second;
};

int main()
{
    
    
    Clock(0,0,0); //调用有参数的构造函数
    Clock my_clock;  //调用无参数的构造函数
    return 0;
}

In the above example, there are two forms of overloaded constructor: parameterized and parameterless (that is, the default constructor)

1.4 The realization of the constructor


Clock::Clock(int NewH, int NewM, int NewS) 
{
    
    
    hour = NewH;
    minute = NewM;
    second = NewS;
}

Second, the copy constructor

There are two ways to make a copy of an object. The first way is to create a new object, then take out the data members of the original object and assign it to the new object. This is obviously too cumbersome, so in order to make a class have the ability to copy objects of this class by itself, the copy constructor is introduced.

2.1 What is a copy constructor?

The copy constructor is a special constructor, which has all the characteristics of a general constructor, and its formal parameters are references to objects of this class.

2.2 Why is there a copy constructor?

The role of the copy constructor is to make an existing object (specified by the parameters of the copy constructor) to initialize a new object of the same kind. If the program does not define a copy constructor of the class, the system will automatically generate a hidden copy constructor when necessary. The function of this hidden copy constructor is to copy each data member of the initial value object to the newly created object. The object thus obtained has the same data members and attributes as the original object.

2.3 The function of the copy constructor

Before explaining the function of the copy constructor, let's take a look at the general method of declaring and implementing the copy constructor:

class 类名
{
    
    
public:
    类名(形参); //构造函数
    类名(类名& 对象名); //复制构造函数
    ...
};

类名::类名(类名 &对象名) //复制构造函数的实现
{
    
    
    //函数体
}

As we know before, the ordinary constructor is called when the object is created, and the copy constructor is called in the following three situations:

Example:

class Point
{
    
    
public:
    Point(int x = 0,int y = 0)
    {
    
    
        _x = x;
        _y = y;
    }
    Point(Point& p); //复制构造函数
    int GetX()
    {
    
    
        return _x;
    }
    int GetY()
    {
    
    
        return _y;
    }

private:
    int _x,_y;
};
  1. When using an object of a class to initialize another object:
int main()
{
    
    
    Point a(1,2);
    Point b(a); //用对象a初始化对象b时,复制构造函数被调用
    Point c = a; //用对象a初始化对象c时,复制构造函数被调用
    return 0;
}

Notes: The above initialization of b and c can call the copy constructor. The two writing methods are equivalent, and the operations performed are exactly the same.

  1. If the formal parameters of the function are objects of the class, when the function is called, the formal and actual parameters are combined:
void Fun(Point p)
{
    
    
    //函数体
}

int main()
{
    
    
    Point a(1,2);
    Fun(a); //函数的形参为类的对象,当调用对象时,复制构造函数被调用.
    return  0;
}

Notes: The copy constructor will only be called when the object is passed by value. If the pass is a reference, the copy constructor will not be called. So this is also the reason why passing by reference is more efficient than passing by value.

  1. If the return value of the function is an object of the class, when the function is completed and returns to the caller:
Point Fun()
{
    
    
    Point a(1,2);
    return a;  //函数Fun的返回值是类的对象,返回函数值的时候,调用复制构造函数
}

int main()
{
    
    
    Point b;
    b = Fun();
    return 0;
}

Q: Why in this case, the copy constructor is called when the function value is returned?

Answer: The function Fun() returns a to the main function, but we all know that a is a local variable of Fun(). When the life cycle of the Fun() function ends, a will die and it is impossible to return to the main function. Continue to survive after the function. So in this case, the compiler will create an unnamed temporary object in the main function. The life cycle of the temporary object is only in b = Fun(). When the statement return a is executed, the copy constructor is actually called to copy the value of a to the unnamed temporary object. When the function Fun() ends, the object a disappears, but the temporary object will exist in b = Fun(). When this expression is calculated, the temporary object has completed its work.

Three, the destructor

We just discussed that when a local variable ends with its function life cycle, the object in the function will disappear, so when the object disappears (such as when constructing an object, use malloc to dynamically apply for it in the function) Space) Who will do these so-called "aftercare" work? In this way we lead to the destructor.

What is a destructor?

Like the constructor, the destructor is usually a public member function of the class. Its name is composed of a "~" in front of the class name, and it has no return value. The difference between a destructor and a constructor is that the destructor does not accept any parameters! (The parameter can be a virtual function). If we don't define the destructor by ourselves, the compiler will also automatically generate a hidden destructor whose function body is empty.

Let's take a look at the declaration of the destructor:

class Clock
{
    
    
public:
    Clock(int NewH,int NewM,int NewS);  //有参数的构造函数
    Clock()   //无参数的构造函数
    {
    
    
        hour = 0;
        minute = 0;
        second = 0;
    }
    void SetTime(int NewH,int NewM,int NewS);
    void ShowTime();
    ~Clock(); //析构函数

private:
    int hour,minute,second;
};

Notes: A destructor with an empty function body does not do nothing.

Tips:
The construction order of the class is constructed in the order of statements.
The destructor call of the class is called in the reverse order of the constructor call
. 1. Global objects are constructed before local objects.
2. Static objects are constructed before ordinary objects.

Guess you like

Origin blog.csdn.net/xhuyang111/article/details/114587797