use of ' this() ' keyword in ctor design

H

hazz

will the third ctor in this class call the first two or just the null ctor?

public class B {
public B() { ... }
public B(string str) {.....}
public B(Token tkn, string str, int int_var) : this() { ... }
}

can I add an argument to this(str) and do the following so that ctor #3 does
call ctor#2 ?

public class B {
public B() { ... }
public B(string str) {.....}
public B(Token tkn, string str, int int_var) : this(str) { ... }
}

thank you, -greg
 
M

Mike Schilling

hazz said:
will the third ctor in this class call the first two or just the null
ctor?

public class B {
public B() { ... }
public B(string str) {.....}
public B(Token tkn, string str, int int_var) : this() { ... }

this() calls only the constuctor with no arguments.
}

can I add an argument to this(str) and do the following so that ctor #3
does
call ctor#2 ?

public class B {
public B() { ... }
public B(string str) {.....}
public B(Token tkn, string str, int int_var) : this(str) { ... }
}

Yes, that's exactly how you do it.
 
S

Steve Willcock

hazz said:
will the third ctor in this class call the first two or just the null ctor?

public class B {
public B() { ... }
public B(string str) {.....}
public B(Token tkn, string str, int int_var) : this() { ... }
}

It will just call the null constructor (public B())
can I add an argument to this(str) and do the following so that ctor #3 does
call ctor#2 ?

public class B {
public B() { ... }
public B(string str) {.....}
public B(Token tkn, string str, int int_var) : this(str) { ... }
}

Yes, in this case, ctor #2 is executed first then ctor #3 is executed - ctor
#1 is not executed
 
T

The Last Gunslinger

hazz said:
will the third ctor in this class call the first two or just the null ctor?

It will call the one that matches the parameters you supplied, so the
zero param constructor.
public class B {
public B() { ... }
public B(string str) {.....}
public B(Token tkn, string str, int int_var) : this() { ... }
}

can I add an argument to this(str) and do the following so that ctor #3 does
call ctor#2 ?
Yes

public class B {
public B() { ... }
public B(string str) {.....}
public B(Token tkn, string str, int int_var) : this(str) { ... }
}

thank you, -greg


JB
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top