10. C ++-constructor initialization list, object construction sequence, destructor, 10. c Constructor

Source: Internet
Author: User
Tags c constructor

10. C ++-constructor initialization list, object construction sequence, destructor, 10. c Constructor

First, recall,Previously learned const

Separate useConst ModificationVariables are defined.ConstantFor example, const int I = 1;

UseVolatile const ModificationVariable is definedRead-Only variables

UseConst & ModifierVariable is definedRead-Only variables

Can a const be defined in a class?Member?

Directly write the code:

#include <stdio.h>class Test{private:  const int ci;public://       Test()//       {//           ci=10;//       }  int getCI()  {       return ci;  }};int main(){       Test t;       printf("%d\n",t.getCI());       return 0;}

Compilation error:

test.cpp: In function ‘int main()’:test.cpp:21: error: structure ‘t’ with uninitialized const members

According to the compilation information, because the const Member of the struct t is not initialized, an error occurred while executing printf.

Next, unmask the preceding example and use the const learned in the previous chapter to initialize the const.

Compilation or error:

test.cpp: In constructor ‘Test::Test()’:test.cpp:8: error: uninitialized member ‘Test::ci’ with ‘const’ type ‘const int’test.cpp:10: error: assignment of read-only data-member ‘Test::ci’

From the compilation information, the const variable cannot be directly initialized in the Test: Test () constructor.

 

So,In C ++Medium,The constructor initialization list (In addition to initializing member variables, you can also initialize a const member.)

Initialization listLocated in the constructor nameRight sideToStart with ColonAnd then the variable to be initialized,Separated by commasFor example:

Class Example {private: int I; float j; const int ci; int * p; public: Test (): j (1.5), I (2), ci (10) // initialize I = 2, j = 1.5, ci = 10 {p = new int; * p = 3 ;}};

Note:

-List member'sInitialization orderOnly for MembersDeclaration OrderSame, irrelevant to the location of the initialization list

For example, in the previous example, the initialization sequence of the initialization list is: I = 2, j = 1.5, ci = 10.

-When the constructor is called for initializationInitialize the list firstAnd then execute the content in the constructor.

 

Is the const member in the class A constant or a read-only variable?

See the following example:

#include <stdio.h>class Test{private:  const int ci;public:      Test():ci(10)      { }  int getCI()  {       return ci;  }  void setCI(int val)  {     int *p=const_cast<int *>(&ci);     *p=val;  }};int main(){    Test t;    t.setCI(5);    printf("%d\n",t.getCI());    return 0;}

Compile and run:

5   

So the const member in the class definesRead-Only variables

 

 

Object Construction Order

Classes in C ++ can define multiple objects. What is the order of Object Construction?

For local objects (stacks)

-When the program executes the Definition Statement of the object, it constructs

For objects created through new (HEAP)

-Like a local object, the new statement is constructed when the program runs.

For global objects (static storage area)

-The object construction sequence is uncertain, so we needAvoidMutual dependency between multiple global objects.

 

Object destruction-Destructor

We have learned how to initialize an object by using constructors.

Similarly, some cleanup work should be performed before the object is destroyed. Therefore, a special cleanup function is introduced in C ++-Destructor

  • Functions and constructor of destructorOppositeAutomatically called when the object is destroyed
  • DestructorNo Parameters, AlsoNo return value type declaration

Definition :~ Class_name (), for example:

Class Test {public: Test () {}// constructor ~ Test () {}// destructor };

Note:

  • In the class, when the Destructor is defined, the compiler will not provide the default constructor, so you need to define a constructor yourself.
  • The object variable created using new must be deleted when not in use before the Destructor can be called.

See the following example:

#include <stdio.h>class Test{  int val;public:  Test(int i)  {    val=i;    printf("Test() val=%d\n",val);   }  ~Test()  {      printf("~Test() val=%d\n",val);  }};int main(){    Test t1(1);    Test* t2 = new Test(2);//  delete t2;    return 0;}

Compile and run:

Test(1)Test(2)~Test(1)

From the print result, we can see that the destructor of t2 is not printed, so it only prints :~ Test (1)

Run again after unblocking:

Test(1)Test(2)~Test(2)~Test(1)

 

Summary:

When there are Members in the class that need memory application, file opening, and database connection, you needDefine destructorTo Recycle resources.

(Similar to the copy 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: info-contact@alibabacloud.com 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.