calling other constructor of same class

  • Thread starter Thread starter Nikola Skoric
  • Start date Start date
N

Nikola Skoric

Lets say I have a situation like this:

public class a {
        public a () {
                //...
        }
         public a (int i) {
                //...
        }
}

Is there a way to call a() from within a(int i)? Basicly what I'm trying
to achieve is to put all the common code in a (), and in a(int i) just
initialize what I can with the i parameter and than call the a()
construcotor. Would that be possible?
 
Nikola said:
Lets say I have a situation like this:

public class a {
public a () {
//...
}
public a (int i) {
//...
}
}

Is there a way to call a() from within a(int i)? Basicly what I'm trying
to achieve is to put all the common code in a (), and in a(int i) just
initialize what I can with the i parameter and than call the a()
construcotor. Would that be possible?

no, you want do do something like this:

public class a
{
public a()
{
function_call();
}

public a(int i)
{
// stuff with i;
fuction_call();
}

private void function_call()
{
// the common functionality of a() and a(int)
}
 
Nikola Skoric said:
Is there a way to call a() from within a(int i)?

public a(int i) : this()
{
// Code dealing with i, to follow the () constructor
}

P.
 
Nikola said:
Lets say I have a situation like this:

public class a {
public a () {
//...
}
public a (int i) {
//...
}
}

Is there a way to call a() from within a(int i)? Basicly what I'm trying
to achieve is to put all the common code in a (), and in a(int i) just
initialize what I can with the i parameter and than call the a()
construcotor. Would that be possible?

Only if you want to call it at the very beginning. Attaching " :
this()" to the end of the constructor method instructs the compiler to
call the overloaded constructor with the proper signature. The second
constructor is called *before* the current constructor. It works
similar to how "public a() : base() " works.

public class a {
public a()
{
}

public a ( int i ) : this()
{
this.i = i;
}
}

--Mike
 
Back
Top