3

I've encountered the following question online.

If we call one constructor from another in a class, what will happen?

Can anyone give me some hints?

methode
  • 5,212
  • 2
  • 30
  • 42
Fihop
  • 3,067
  • 7
  • 38
  • 64

2 Answers2

4

in java also its possible with the power of the this keyword. check out the example given 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 it's c# i found this saying it's possible Is nesting constructors (or factory methods) good, or should each do all init work

Community
  • 1
  • 1
Mightian
  • 7,149
  • 3
  • 39
  • 50
1

This example from MSDN clarifies it

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

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 from Can I call a constructor from another constructor (do constructor chaining) in C++? too.

Community
  • 1
  • 1
Shreevardhan
  • 11,453
  • 3
  • 36
  • 47