C + + constructors and destructors

Source: Internet
Author: User

constructor Function:

Role:

1) Allocate space: Allocate storage space for non-static data members

2) Initialize member: Initialize non-static data member

Allocate space:

1) Contains pointer variables, requires the programmer to explicitly request space (using new application)

2) Non-pointer variable: Automatic allocation of space by the system

Initialize Members:

1) Initialize with assignment statement: general variables

2) Initialize with expression table: Generic variable + const member, reference member, object member

Call timing: When defining an object, the system automatically calls the constructor

1) When an object is created, the constructor is called automatically

Coord P1 (1);

Coord p2=1; The constructor is also called , but there is a precondition: the constructor parameter can have only one parameter

2) If the object is created with new, the constructor is called automatically.

Syntax: same name and class name, no return type, function allowed as inline function, overloaded function, with default parameter value

Code:

    Class A      {      private:          int x;          int& Rx;           const float PI;      Public:          A (int x1): Rx (x), pi (3.14)//rx (x) equivalent to RX=X,PI (3.14) equivalent to pi=3.14          {              x=x1;//general variable          }                                           };      Call: A A (10);  

Use of member initialization tables

Grammar:

Class Name:: constructor name (parameter table):( data member name 1 (initial value 1), data member name 2 (initial value 2),...... )

{

function body

}

Description

1. initialization of Class members : initialized according to the order in which they are declared in the class , regardless of their order in the Member initialization table

2. when a data member contains an array, it should be implemented through an assignment statement in the constructor and cannot use the Member initialization table

Destructors : Handling the aftermath

function: free space:

1) contains pointer variables that require the programmer to explicitly free up space

2) Non-pointer variable: The system automatically frees up space

Call Time:

1) When the object is revoked, as the object is defined within the function, when the function call ends, the object is revoked.

2) If the object was created with new, the destructor is called automatically when it is delete.

syntax: no return type, no parameters, function name is the class name before the "~"

Code:

    Class X      {public      :          x ()  {}          ~x () {}      };   

Description

1, why do you want to define the destructor as virtual function?
Because: virtual function is to support polymorphism, ... Then add

Problems encountered

    #include <iostream>      using namespace std;      Class AAA      {public      :          aaa (void);          ~aaa (void);      };            AAA::AAA ()      {            };            int main ()      {          AAA t;  Error          AAA *p = new AAA ();//No Error          System ("pause");          return 1;      }  

Problem analysis: Because the compiler declares a default constructor and destructor for each class, copy constructors, assignment operators . When the user defines it themselves, the system is not automatically generated for the class. Constructors and destructors are already defined in the class, and the system does not generate itself.

AAA t;//Error

Cause: When you define an object on the heap, the constructor and destructor are called automatically by the system. When linking, the system will find that the implementation of the destructor is not found, this will be an error, saying that the destructor is not found . But if you can't find it, you'll get an error.

AAA *p = new AAA (); No error

Cause:The constructor is called when new, but the destructor is not used because there is no delete because the user needs to release it manually. When the program is linked, no destructor is used, and there is no error to find the implementation.

    int main ()      {          //aaa t;  Error          AAA *p = new AAA ();           Delete p; Error          System ("pause");          return 1;      }  

As on the example above, if you write the delete

AAA *p = new AAA (); No error

Delete p;

when the program executes the delete, the destructor is required . Link, the system will find its implementation. When the discovery is not realized, and error.

Therefore, we declare the function to remember the implementation, especially the constructors and destructors, copy constructors, assignment operators.


C + + constructors and destructors

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.