"Go" How to call another constructor in a constructor in C + +

Source: Internet
Author: User

In C + +, a class's constructor cannot directly invoke another constructor, such as:

1 #ifndef _a_h_2     #define_a_h_3#include <stdio.h>4#include <New>5     classA6     {7      Public:8 A ()9             {Tenprintf"In A::(). m_x=%d\n", m_x); OneA0); Aprintf"Out A::(). m_x=%d\n", m_x); -  -             } the  -  -Aintx) -             { +printf"In A::(int x). x=%d\n", x); -m_x=x; +             } A  at     Private: -             intm_x; -};

Here the 11th line calls a (0); just constructs a temporary object, and does not call a (int x) to initialize itself. The result of the operation is:

[Email protected] utcov]#./utest.  out In A::(). m_x=4268020inA::(int x). x=0outA::(). m_x=4268020

As you can see, although a (0) is called, m_x still does not change, which is 4268020.
The correct approach is to use placement NEW:

1     //A.h2 #ifndef _a_h_3     #define_a_h_4#include <stdio.h>5#include <New>6     classA7     {8      Public:9 A ()Ten             { Oneprintf"In A::(). m_x=%d\n", m_x); A                     New( ThisA0); -printf"Out A::(). m_x=%d\n", m_x); -  the             } -  -  -Aintx) +             { -printf"In A::(int x). x=%d\n", x); +m_x=x; A             } at  -  -     Private: -             intm_x; -     }; -  in     #endif

The 11th line shall be: New (This) A (0); That is, the constructor a (int x) is called with the current object to construct a "new" object. The result of the operation is:

    [Email protected] utcov]#./utest.  out In     A::(). m_x=4268020in    A::(int x). x=0out    A::(). m_x=0

As you can see, the current object is indeed changed.

"Go" How to call another constructor in a constructor in C + +

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.