Re: Why can't I call a parameterless-constructor from a baseclass ?

Tech-Archive recommends: Repair Windows Errors & Optimize Windows Performance




AndreasW wrote:
Hi,

internal static class Program
{

public class foo
{
private int _id;
public foo()
{
}
public foo(int _id)
{
this._id = _id;
}
}
public class bar : foo
{


}
[STAThread]
private static void Main()
{
bar b = new bar(3); // constructor canot be found
}
}

why is this code not allowed ?

.... because in C# constructors are not inherited. If you want a
constructor for bar that takes an int, you have to say this:

public bar(int id) : base(id) { }

* I should add a note about "constructors are not inherited": if you do
not specify any constructor at all for a class, the compiler infers the
following:

public bar() : base() { }

If you then insert the int constructor, as above, you'll lose this
default constructor unless you explicitly write it. So, at the end of
it all, of you want bar to have constructors as foo, you need to say:

public bar() : base() { }
public bar(int id) : base(id) { }

By the way, one typically does not use the _ prefix for method
parameter names, just for private field names, so your foo constructor
would be better written as:

public foo(int id)
{
this._id = id;
}

.



Relevant Pages

  • Re: C++ design question
    ... so anyone can instantiate it without ... > default constructor in the class header rather that allowing it to be ... > separately and initialize a pointer to it in Foo: ... fooDeriveN::DoStuffWithBarBase() at all because we have a Bar* in Foo*. ...
    (comp.object)
  • Re: static virtual/override
    ... > I sorely miss the feature that permits ... > public class Bar: Foo ...
    (microsoft.public.dotnet.languages.csharp)
  • Re: getting used to Java - question about "style"
    ... > constructor." ... Let's suppose you create a class Foo ... ... They can also override frob(), because we didn't make it private or final. ... When a new object of type Bar is created, ...
    (comp.lang.java.programmer)
  • Re: Opposite of typeof /GetType()
    ... protected T bar() ... public class SuperFoo: Foo ... public foo bar() ...
    (microsoft.public.dotnet.languages.csharp)
  • Re: C++ design question
    ... The default constructor is implied in the initialization list. ... One wants to access Bar at the superclass level to avoid static typing ... Usually that would be done by whoever instantiates a Foo subclass ...
    (comp.object)