C + + Note----constructor and destructor (ii)

Source: Internet
Author: User

A constructor is a special member function. Called automatically when the object is created, initializing the data members of the object.

(1) The object created in the stack will automatically call the destructor at the end of the lifetime.

(2) The object created on the heap, to be displayed by the programmer, calls delete to release the object while invoking the destructor.

(3) The construction of the global object precedes the main function. The global object also automatically calls the analysis constructor at the end of its lifetime to release the object.

Functions of constructors: initialization, type conversion (conversion constructors)

1. Conversion constructor

Definition: A transformation constructor is a constructor of a single parameter

Role: Converting other types to class types

The constructor of a class has only one parameter that is very dangerous, because the compiler can use this constructor to implicitly convert the type of the argument to the class type

The constructors with one parameter are:

Common constructors

Conversion constructors (initialization, type conversions)

2. Difference between assignment and initialization

The equals sign in the initialization statement is not an operator. The compiler has a special explanation for this representation

Assignment test& test::operator= (const test& Other);

3.explicit

Keywords that are only available to constructors of classes

The compiler does not use a constructor declared as explicit for implicit conversions, it can only display the created object in program code

C + + Note----constructor and destructor (ii)

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.