Call one constructor from other constructors in the same class

I came across the following question on the internet.

If we call one constructor from another in the class, what happens?

Can anyone give me some advice?

+3


source to share


2 answers


in java it is also possible with the keyword this

. check the example below.

public class A {

    public A() {
        //this("a");
        System.out.println("inside default Constructor");
    }

    public A(String a){
        this();
        System.out.println("inside Constructor A");
    }

}

      



This concept is called constructor chaining . If this is C # I found this saying it is possible Are nested constructors (or factory methods) good, or each should do all init

+4




This example from MSDN clarifies it

To add delegating constructors, the syntax is used constructor (. . .) : constructor (. . .)

.



class class_a {
public:
    class_a() {}
    // member initialization here, no delegate
    class_a(string str) : m_string{ str } {}

    // can’t do member initialization here
    // error C3511: a call to a delegating constructor shall be the only member-initializer
    class_a(string str, double dbl) : class_a(str) , m_double{ dbl } {}

    // only member assignment
    class_a(string str, double dbl) : class_a(str) { m_double = dbl; }
    double m_double{ 1.0 };
    string m_string;
};

      

Read answers Is it possible to call a constructor from another constructor (constructor chaining) in C ++? also.

+1


source







All Articles