Basic notes: constructor, copy constructor, and destructor

Source: Internet
Author: User


The main function of the constructor is to allocate space for the object, and the data members of the class can also be initialized. Constructor has the following properties:

1. the constructor name must be the same as the class name.

2. constructor parameters can be of any data type, but they do not return values. They cannot be defined for them, including void.

3. When an object is created, the compilation system automatically calls the constructor to allocate and initialize the object memory. (If it is a system default constructor, the member variables are initialized to random values that are meaningless)

4. constructor is a member function of a class. It has all the properties of a common member function and can be any member of a Member class. It can be an inline function, a parameter table, a default parameter value, or a reload.

Constructor with default parameters

You can include the default parameter values during declaration or definition. In this way, you can use the default parameter value to initialize data members without specifying real parameters when defining objects.

Example 1 (default ):

#include<iostream> using namespace std; class Rectangle {       double length,width;       public:              Rectangle(double a=0.0,double b=0.0);              double area();       }; Rectangle::Rectangle(double aa,double bb) {                             length = aa;                             width = bb;                             } double Rectangle::area() {        double s;        s = length * width;        return s;        }         int main() {     Rectangle ob1;     Rectangle ob2(2.5);     Rectangle ob3(5.0,4.0);     cout<<ob1.area()<<endl;     cout<<ob2.area()<<endl;     cout<<ob3.area()<<endl;     system("pause");     }

Example 2 (default ):

# Include <iostream> using namespace STD; Class rectangle {double length, width, value; public: rectangle (double A, double B); double area () ;}; rectangle :: rectangle (double AA, Double BB = 10) // defines the constructor with default parameters {length = AA; width = BB;} double rectangle: Area () {return length * width;} int main () {rectangle ob2 (2.5), ob3 (5.0, 4.0); cout <ob2.area () <Endl; cout <ob3.area () <Endl; System ("pause ");}

Copy constructor

Create an undefined new object with known objects.

Form of custom copy constructor:

Class Name (Class Name & object name)


Function body


If no custom copy function is available, the system automatically calls the default copy constructor. The default constructor is a shortest copy function. (The new and old objects point to the same reference ).

In general, the copy constructor will be called in the following three cases:

1. When another object of the class is initialized with the class object.

2. The form parameter of a function is a Class Object. When the form parameter and the real parameter are combined during the function call process.

3. the return value of a function is a class object.

# Include <iostream> using namespace STD; Class dot {PRIVATE: int A, B; public: dot (INT x = 0, int y = 0) {A = X; B = y ;}dot (DOT & D); int geta () {return a ;}int getb () {return B ;}; Dot :: DOT (DOT & D) {A = D. A + 10; B = D. B + 10; cout <"Call copy constructor" <Endl;} void F (DOT p) {cout <p. geta () <"" <p. getb () <Endl;} dot g () {dot Q (3, 5); Return Q;} int main () {dot dt1 (2, 4); dot dt2 (dt1 ); // cout <dt2.geta () <<"" <Dt2.getb () <Endl; F (dt2); // call cout in 2nd cases of copying constructors <dt2.geta () <"" <dt2.getb () <Endl; dt2 = g (); // 3rd cases of calling the copy constructor // This error is reported in Dev C ++. No error is reported in vc60. No matching function for call to 'dot: dot (DOT) 'cout <dt2.geta () <"" <dt2.getb () <Endl; dt2 = dt1; // bit copy. It is useless to call the copy constructor for value transfer !!!!!!! Because dt2 already exists before that. Cout <dt2.geta () <"" <dt2.getb () <Endl; dot dtx = dt1; // before this dtx does not exist, the copy constructor is called. If the code is written as Dot dtx; dtx = dt1; then the copy constructor is not called, which is the same as the code in dt2 = dt1. Cout <dtx. Geta () <"" <dtx. getb () <Endl; System ("pause ");}

Demo in thinking in C ++:

#include<fstream>using namespace std;ofstream out("Howmany2.out");class Howmany2{      string name;      static int objectCount;      public:             Howmany2(const string& id=""): name(id){                            ++objectCount;                            print("Howmany2()");                            }             ~Howmany2(){                         --objectCount;                         print("~Howmany2()");                         }             Howmany2(const Howmany2& h):name({                        name+=" copy";                        ++objectCount;                        print("Howmany2(const Howmany2&)");                        }             void print(const string& msg="")const{                  if(msg.size()!=0)                       out<<msg<<endl;                       out<<'\t'<<name<<":"<<"objectCount="<<objectCount<<endl;                  }      };int Howmany2::objectCount=0;Howmany2 f(Howmany2 x){         x.print("x argument inside f()");         out<<"Returning from f()"<<endl;         return x;          }int main(){    Howmany2 h("HK");    out<<"Entering f()"<<endl;    Howmany2 h2=f(h);    h2.print("h2 after call to f()");    out<<"Call f(),no return value"<<endl;    f(h);    out<<"after call to f()"<<endl;    }

The result is as follows:

Howmany2()HK:objectCount=1Entering f()Howmany2(const Howmany2&)HK copy:objectCount=2x argument inside f()HK copy:objectCount=2Returning from f()Howmany2(const Howmany2&)HK copy copy:objectCount=3~Howmany2()HK copy:objectCount=2h2 after call to f()HK copy copy:objectCount=2Call f(),no return valueHowmany2(const Howmany2&)HK copy:objectCount=3x argument inside f()HK copy:objectCount=3Returning from f()Howmany2(const Howmany2&)HK copy copy:objectCount=4~Howmany2()HK copy copy:objectCount=3~Howmany2()HK copy:objectCount=2after call to f()~Howmany2()HK copy copy:objectCount=1~Howmany2()HK:objectCount=0


1. The Destructor cannot be overloaded, and there is only one destructor in a class.

2. When the object is revoked, the system automatically calls the destructor to release the space and complete the aftermath.

3. Each class requires a destructor. If it is not explicitly defined, the system automatically generates a default destructor, which is an empty function.

4. For most classes, the default destructor can meet the requirements. However, if the object needs to be processed internally before the operation is completed, the defined destructor should be displayed.

5. A common usage of constructor and destructor is to use the new operator in the constructor to allocate space for objects and use the delete Escape Character in the destructor to release space. (Use new to create an object to call the constructor, and use Delete to destroy an object to call the destructor ).


#include <iostream>  using namespace std;   class B{public:B(){cout<<"B"<<endl;}~B(){cout<<"~B"<<endl;}};class C:public B{public:C(B &b):b_(b){cout<<"C"<<endl;}~C(){cout<<"~C"<<endl;}private:B b_;};int main(int argc, char* argv[]){//cout<<sizeof(A)<<endl;B b;C d(b);system("pause");return 0;}

In the preceding example, 1st B is generated when B is created.

2nd B and 1st C are generated when c d (B. In the initialization expression table, B _ (B) does not call the constructor of B, but calls the default copy constructor of B.

In the destructor, all objects call the destructor, which is in the opposite order of the constructor.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.