-1

I have this code:

class Parent
{
    public Parent(string someArg)
    {
        Console.WriteLine("Parent");
    }

}

class Child : Parent
{
    public Child(string someArg)
    {
        Console.WriteLine("Child");
    }
}

which I then instantiate:

var child = new Child("something");

gets me an error. I know it has to do with the parent constructor, but I'm not sure why is this the case. Am I required to use base every time I have a constructor in the parent which is not parameter-less? Why?

daremkd
  • 8,244
  • 6
  • 40
  • 66
  • Please state what error is returned. – Tony Hinkle Mar 04 '16 at 18:59
  • 1
    change it to `public Child(string someArg):base(someArg)` to call the constructor of the parent class. – juharr Mar 04 '16 at 19:01
  • Possible duplicate of [C# - Making all derived classes call the base class constructor](http://stackoverflow.com/questions/4296888/c-sharp-making-all-derived-classes-call-the-base-class-constructor) – kayess Mar 04 '16 at 19:08

3 Answers3

5

The base class needs initialization just as well. Therefore, when the base class only has a constructor with an appetite for parameters, you will have to feed it.

In this case, if you are overriding everything the baseclass constructor does, you could let the baseclass have a second, parameterless, constructor. And if you'd like to make use of the logic in the baseclass constructor, you really have no choice but to call : base(string)

Allmighty
  • 1,499
  • 12
  • 19
1

When you declare a class it has a default parameterless constructor. If you define your own construct then default one is gone. In your case you defined a constructor with a parameter.

When you create a new instance each class in inheritance hierarchy should be constructed. Base class has the only constructor with a string parameter which is not called in your code. The implicit parameterless constructor call cannot happen as well.

So that's why you should white:

public Child(string someArg) :base(someArg) { }

Or you can bring the parameterless constructor back in you code and do not use base:

public Parent() { }
Ivan Gritsenko
  • 4,166
  • 2
  • 20
  • 34
0

Add this at base class to solve your problem.

public Parent() {}

or make it protected to use it just for child classes

protected Parent() {}
M.kazem Akhgary
  • 18,645
  • 8
  • 57
  • 118