C ++: call another constructor In the constructor of the class.

Source: Internet
Author: User
In Java, it is often visible that the constructor of the class calls another constructor. However, in C ++, this requirement is greatly reduced because the constructor allows default parameters. In this case, we may occasionally want to call another constructor in the class constructor. We know that when constructing an object, we will do two things: 1. allocate memory 2 and execute the constructor; so the key to calling another constructor In the constructor is to let the second constructor execute on the memory allocated for the first time, instead of allocating new memory, this can be done using placement new in the Standard Library:

Let's take a look at the definition of placement new in the standard library.
Inline void * _ cdecl operator new (size_t, void * _ p)
{Return (_ p );}

No new memory is allocated.

# Include

Class My
{
Public:
My ()
{
New (this) My (5 );
}

My (int I)
{
A = I;
}

Int;
};

Note that if a member variable is initialized in the first constructor and another constructor is called, the same member variable is initialized in the constructor, this will cause the same member variable to be initialized twice. But this problem also exists in Java, so pay attention to the sequence during programming.

Related Article

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.