Simple question on constructor

  • Thread starter Thread starter DBC User
  • Start date Start date
D

DBC User

I have 2 constructors in my class, first one with no paramter and the
second one is with a paramter. I want the later constructor to use the
first constructor and do some more with the parameter. How can I do
this?

eg:

public const()
{
//do base work
}

public const(string data)
{
//do base work --- Here is where I want to reuse the default
constructor
path = data;
}

It is a simple one but somehow I am not getting it correct.

Thanks.
 
You can do this in one to two ways:

1. Call the base constructor (parameterless) one from the additional one:

public const(string data) : this()
{
}

or,

2. Call the additional constructor from the base one with a default value
(probably null ???):

public const() : this(null)
{
}

James
 
DBC User said:
I have 2 constructors in my class, first one with no paramter and the
second one is with a paramter. I want the later constructor to use the
first constructor and do some more with the parameter. How can I do
this?

IMHO, it is better to have the parameterless constructor call the one with
parameters, passing a default value. For example:

public const() : this("default string")
{
}

public const(string data)
{
}

(ignoring for the moment that I would never call a class "const" :) ).

Pete
 
Back
Top