C + + Overloaded constructors cannot be called to each other

Source: Internet
Author: User

Overloaded constructors in Java classes can call each other, as in the following code:

1  Public classTestConstructor {2     Private intvalue;3 4      PublicTestConstructor (intvalue) {5          This. Value =value;6System.out.println ("Constructor1:" + This);7     }8 9      PublicTestConstructor () {Ten          This(10); OneSystem.out.println ("Constructor2:" + This); A     } -  -      Public Static voidMain (string[] args) { theTestConstructor test =NewTestConstructor (); - System.out.println (test.value); - System.out.println (test); -     } +}

The result of the code execution is:

Constructor1:[email protected]
Constructor2:[email protected]
10
[Email protected]

The visible result is expected, the value assignment is successful, and only one object is created.

Consider the C + + implementation (header file omitted):

1#include"Testconstructor.h"2#include <QDebug>3 4 Testconstructor::testconstructor ()5 {6 //This (ten);7TestConstructor (Ten);8Qdebug () <<"Constructor1:"<< This;9 }Ten  OneTestconstructor::testconstructor (intvalue) A { -      This->value =value; -Qdebug () <<"Constructor2:"<< This; the}
1#include"Testconstructor.h"2#include <QDebug>3 4 intMainintargcChar*argv[])5 {6TestConstructor *t =NewTestConstructor ();7Qdebug () <<t->value;8Qdebug () <<T;9     DeleteT;Ten}

The result of the code execution is:

Constructor2:0x22fcf0

Constructor1:0xdadfb0

15574896

0xdadfb0

On the one hand, the value set values are not in effect, and on the other hand, two constructors create two different objects, stating that C + + cannot be called from one another in Java-like constructors.

Workaround:

The requirement for most constructors to call each other should be a default parameter, which can be set directly in the function declaration of C + + (Java does not support default parameters) so that no constructor overloads are required:

TestConstructor (int value = 10);

  

C + + Overloaded constructors cannot be called to each other

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.