Parent does not contain constructor that takes 0 arguments - c#

If I have this code in C#:
public abstract class Parent
{
private int x;
public Parent(int x)
{
this.x = x;
}
public abstract void foo;
}
public class Child
{
public override void foo()
{
x = x + 10;
}
}
I get error that:
Parent does not contain constructor that takes 0 arguments.
How can I fix it, without creating non-parametric constructor?

You can create a constructor in Child, e.g.
public Child(int x) : base(x)
{
}
Constructors are not inherited - but if you don't supply any constructors at all, the C# compiler tries to create one equivalent to this:
public Child() : base()
{
}
That's what's failing here, because there isn't a parameterless base constructor to call.
Your derived class constructor doesn't have to have the same parameters as the base class constructor of course - so long as it passes appropriate arguments to a base constructor, that's fine. For example, you could write:
public Child() : base(0) // Default to x = 0
{
}
See my article on constructors for more details.

By manually invoking Parent's constructor:
public class Child: Parent {
public Child( )
: base(0) { }
public override void foo( ) {
x = x + 10;
}
}

That is because there is an Implicit call to a constructor with zero argument.
So you need to add an explicit call:
public Child(int x) : base(x)
{
}
Or instead, you can add zero argument contructor in parent itself:
public parent() { }

Related

Passing child method to base constructor

I have a base class that implements some logic and eventually calls an Action which was passed to the contructor.
public class BaseClass
{
private Action action;
public BaseClass(Action someAction)
{
action += someAction;
}
private void doStuff()
{
action();
}
}
Now I want to derive some child classes that implement some specific logic. In these child classes I have a method for that logic and my attempt was to pass this method to the base constructor. But this result in a compiler error CS0120: An object reference is required for the nonstatic field, method, or property 'member'.
public class SpecificClass : BaseClass
{
private int b;
public SpecificClass(int i)
: base(doSpecificStuff) // <-- compiler error CS0120 here
{
b = i;
}
private void doSpecificStuff()
{
// do something depending on b
}
}
I don't quite get why it fails at that point. Is it because the base constructor gets called first which means when calling it I do not have an instance of the child class (including the child's method)?
But why does the compiler asks for a reference to a nonstatic field? Actually I don't see anything static here. Is there a way to get a reference to doSpecificStuff at that point? this.doSpecificStuff does not work, resulting in CS0027: Keyword 'this' is not available in the current context.
Any suggestions for a better design?
This is exactly where object-oriented-design (OOP) and one of its principles, Polymorphism, comes in place, and what it was designed for.
By making doStuff virtual in the base class, we can override the method in the specific class and customize its behavior.
public class BaseClass
{
private Action? action;
public BaseClass(Action someAction)
{
action += someAction;
}
protected BaseClass()
{
}
protected virtual void doStuff()
{
action?.Invoke();
}
}
public class SpecificClass : BaseClass
{
private int b;
public SpecificClass(int i)
{
b = i;
}
protected override void doStuff()
{
// do something depending on b
}
}
I don't quite get why it fails at that point. Is it because the base constructor gets called first which means when calling it I do not have an instance of the child class (including the child's method)?
Sort of. There is actually an instance of the child class (the object is created immediately of the "right" type) but you can't refer to anything specific to the instance in the constructor initializer.
From section 15.11.2 of the draft C# 6 spec:
An instance constructor initializer cannot access the instance being created.
The best way of handling this really depends on the broader context. For example, you could accept a Func<BaseClass, Action> instead and cast:
public class BaseClass
{
private Action action;
public BaseClass(Func<BaseClass, Action> actionProvider)
{
action += actionProvider(this);
}
private void doStuff()
{
action();
}
}
... then:
public class SpecificClass : BaseClass
{
private int b;
public SpecificClass(int i)
: base(x => ((SpecificClass) x).doSpecificStuff)
{
b = i;
}
private void doSpecificStuff()
{
// do something depending on b
}
}
That's a bit tortuous though. If the action is always expected to be a method in the derived class, an option would be to create an abstract method in the base class and just override it in the derived class instead.
The error message means that the compiler is expecting this:
private static void doSpecificStuff()
{
// do something depending on b
}
Why? because when you call your action in doStuff, C# has no way to now that doSpecificStuff has to be called on the current (this) instance.
To compile, you would have to do something like this :
public class BaseClass
{
private Action action;
public BaseClass(Action<BaseClass> someAction)
{
action += () => someAction(this);
}
private void doStuff()
{
action();
}
}
public class SpecificClass : BaseClass
{
private int b;
public SpecificClass(int i): base(x => ((SpecificClass)x).doSpecificStuff()) // <-- compiler error CS0210 here
{
b = i;
}
private void doSpecificStuff()
{
// do something depending on b
}
}
I do not know exactly why you came up with this approach but why not just us inheritance? (Again, there might be some specific need I'm not aware of here, I'm just mentioning this for the record to post an answer as complete as possible) For instance:
public class BaseClass
{
public BaseClass()
{
}
protected virtual void doStuff()
{
// Doing stuff...
}
}
public class SpecificClass : BaseClass
{
private int b;
public SpecificClass(int i): base()
{
b = i;
}
protected override void doStuff()
{
// do something depending on b
base.doStuff()// if needed...
}
}

Base() and This() in constructors. (Chained constructors)

I have a question regards chaining constructors I read some question on StackOverflow and some c# articles but I cannot understand the topic fully. So I have a BaseClass that is inherited by DerivedClass. In the DerivedClass, I have no argument constructor but it's calling the base constructor using: base() and it also passing a value. Is this the primary purpose of the base keyword used in the constructor to pass a value to the inherited class from the derived one or is something more out there. And also in the derived class, we have a second constructor that takes 1 parameter and its using: this(). I can't understand why when I remove: this() from this constructor "VS" tells me "There is no argument given that corresponds to the required formal parameter "i" of BaseClass.BaseClass(int) ? Why I can't just have one argument constructor in the DerivedClass without using this()?
public class BaseClass
{
protected int _Num;
public BaseClass(int i)
{
_Num = i;
}
public int Num { get => this._Num ; set => _Num = value; }
}
public class DerivedClassA : BaseClass
{
private string _Name;
private int _AnotherValue;
public string Name { get => this._Name ; set => this._Name = value; }
public int AnotherValue { get => this._AnotherValue; set => this._AnotherValue = value; }
public DerivedClassA() : base(123)
{
_Name = "testing";
}
public DerivedClassA(int param2) : this() <-- Why i can't compile the program without the this() keyword here ?
{
AnotherValue = param2;
}
}
public class Program
{
public static void Main(string[] args)
{
DerivedClassA objA = new DerivedClassA(5);
}
}
I can't find a duplicate that exactly matches, so I'll provide an answer.
Imagine these classes:
public class Base
{
public Base()
{
}
}
public class Derived : Base
{
public Derived()
{
}
}
Try it online
When you initialize a derived class, you have to first initialize the base. In our example above, the Base class has a parameterless constructor, so the derived class can implicitly call it. If we add a base second constructor, this logic remains true, and the parameterless constructor will still be implicitly called:
public class Base
{
public Base()
{
}
public Base(int a)
{
}
}
public class Derived : Base
{
public Derived()
{
}
}
Try it online
But if we take away the parameterless constructor, Derived must now call the base constructor explicitly:
public class Base
{
public Base(int a)
{
}
}
public class Derived : Base
{
public Derived() : base(1)
{
}
}
Try it online
So what happens if we add an extra derived class constructor? Well, that also has to call the base class (either directly, or indirectly):
public class Base
{
public Base(int a)
{
// this method body is executed first
}
}
public class DerivedA : Base
{
public DerivedA(string name, int val) : base(val)
{
// this method body is executed second (last if you used this constructor, e.g. new DerivedA("hello", 1) )
}
public DerivedA() : this("test", 5) // this will call the constructor above, which will first call base. So the final chain is: base, constructor above, this constructor
{
// this method body is executed third (last if you used this constructor, e.g. new DerivedA() )
}
}
public class DerivedB : Base
{
public DerivedB(string name, int val) : base(val)
{
}
public DerivedB() : base(5) // this will call the base constructor, and then this constructor. The constructor above will not be used.
{
}
}
Try it online
Note that all classes have a parameterless constructor when no other constructor is defined, so the following two examples are equivalent:
public class BaseA
{
}
public class BaseB
{
public BaseB()
{
}
}
You'll note that SharpLab shows the compiler removed the empty constructor from BaseB() since it's superfluous.
Finally, a derived class without an explicitly defined constructor, will still call the base class constructor implicitly:
public class Base
{
public Base()
{
// this method body is executed first
Console.WriteLine("Base constructor");
}
}
public class Derived : Base
{
}
Try it online
So to summarise: unless your base class has a parameterless constructor, your derived class constructors have to either call a base constructor directly, or indirectly through another derived class constructor. Obviously you only need to call a single base constructor method, as with any other class instantiation. You don't need matching derived methods for each base method, so long as you can construct the base with the values you do have.

Constructor in C#

I have a parent class with 2 constructor and the derived class trying to call the constructor of parent in 2 different methods
public class Parent
{
public Parent()
{
//some stuffs
}
public Parent(string st)
{
//some stuffs
}
}
Now I have a derived class with two methods.
I Have to use Parent-constructor in one method and the Parent(string st) in other method.
But here It is always calling the Parent-constructor. Below is the derived class
public class Derived : Parent
{
public void GetData()
{
//Here I initialize the constructor like this
Parent p = new Parent();
}
public void GetData1()
{
string s = "1";
Parent p = new Parent(s);
}
}
Please let me how to make this happen.
Thanks in advance.
Just have two constructors in your Derived class that use the appropriate constructor in the base.
public class Derived : Parent
{
public Derived() : base()
{
}
public Derived(string s) : base(s)
{
}
}
The :base() nomenclature will invoke the parent constructor.
Use the parent constructor call "base"
public class Parent {
public Parent() {}
public Parent(string s) {}
}
public class Child : Parents {
public Child():base() // Call Parent empty constructor
public Child(string s): base(s) // Call Parent Constructor with parameter
}
Your error comes because you're instanciate a new Object Parents in your Child.
With Base(), you call the parent constructor without instanciate him.
Calling new Derived() will call the Parent() ctor because it inherits from Parent and has an implicit Derived() : base().
After you have constructed Derived() calling the method (not constructor) GetData1() will call the Parent(string st) constructor
These are completely separate routes of constructing parent and it seem you are confusing them
The Parent() constructor is always called because you Derived derives from Parent but doesnt include a constructor, hence a default constructor is created, which calls the parameterless parent constructor.
The call to Parent p = new Parent(s); will call the constructor of Parent that takes a parameter.
If you want to call the parent constructor when creating a Derived object, you have to chain the constructors using base().
public class Derived : Parent
{
public void Derived()
: base()
{
//code
}
public void Derived(string s)
:base(s)
{
//code
}
}

Block base constructor to child class

I'm sure this question is somewhere else but can't find it.
I have an abstract class that will be the base for other classes.
want for the base class to have its base constructor inaccessible, and for the child classes not being able to edit the behavior, forcing them to use another constructor.
public abstract class BaseClass
{
protected int X;
private BaseClass() { } // Problematic accessor
public BaseClass(int x)
{
X = x;
}
}
public class Child : BaseClass
{
public Child(int x)
{
X = x + 5;
}
}
If I set the BaseClass() base constructor private it doesn't compile, but if I set it to protected, Child can override it.
There is a way to block Child modifying the base constructor?
EDIT: I want the base constructor to be inaccessible outside the class too.
If you don't want do anything in the
BaseClass()
constructor, just remove it (BaseClass has an explicit constructor and that's why doesn't have a default one):
public abstract class BaseClass
{
//TODO: probably you want a property to read X
private int X; // <- private looks better for fields
public BaseClass(int x)
{
X = x;
}
}
As for Child class you have to invoke its base constructor, i.e. base(int x):
public class Child : BaseClass
{
public Child(int x)
: base(x + 5) // since X is private, let's move logic into the call
{
}
}
You need to use the correct base class constructor to do what you want:
public class Child : BaseClass
{
public Child(int x) : base(x)
{
X = X + 5;
}
}
Note that the Child constructor body now uses the protected field X, not the parameter x.
Just omit the parameter-less constructor altogether. Now, every derived class is forced to call public BaseClass(int x).

Pass a derived class reference to a base class reference

Pass a derived class reference to a base class reference
does this means that call a base class from the derived class, like the constructor triangle will call the base class?
class Shape {
public int width, height;
public Shape(int x) {
width = height = x;
}
}
class Triangle : Shape {
public string style;
public Triangle(int x) : base(x) {
style = "isosceles";
}
}
Yes, it will instruct the runtime to invoke that base Shape constructor before Triangle's.
The logic executes in this order:
Execute Shape(int x)
Execute Triangle(int x)
You can therefore direct calls to different constructor overloads if you have them. Also note that if your base class has a parameterless constructor, there's essentially an implicit base() added if you do not specify one. That means if your base class does not have a parameterless constructor, all subclasses must make a valid base(...parameters...) in their constructor.
Also, you can use this() instead of base to target a constructor on the current subclass class.
public class MyBaseClass
{
public MyBaseClass()
{
Console.WriteLine("MyBaseClass Parameterless");
}
public MyBaseClass(string message)
{
Console.WriteLine("MyBaseClass Message: " + message);
}
}
public class MySubClass
{
public MySubClass()
{
Console.WriteLine("MySubClass Parameterless");
}
public MySubClass(string message)
: base(message)
{
Console.WriteLine("MySubClass Message: " + message);
}
public MySubClass(bool someUselessFlag)
: this()
{
Console.WriteLine("MySubClass bool someUselessFlag constructor");
}
}
The outputs would be:
var a = new MySubClass();
//outputs:
//MyBaseClass Parameterless
//MySubClass Parameterless
var b = new MySubClass("Hello World!");
//outputs:
//MyBaseClass Message: Hello World!
//MySubClass Message: Hello World!
var c = new MySubClass(true);
//outputs:
//MyBaseClass Parameterless
//MySubClass Parameterless
//MySubClass bool someUselessFlag constructor
Constructors chain on themselves until they eventually call the Object() base constructor. That's why var c = new MySubClass(true) calls more than two constructors.
With the help of the book C# 4.0 - The Complete Reference by Herbert Schildt. I'll try to answer this question. I think the example of the question is incomplete. If this question was raised while reading one of Herbert Schildt's C# book. Then the example may be like this:
class Shape
{
public int width, height;
public Shape(int x)
{
width = height = x;
}
public Shape(Shape shape)
{
width = shape.width;
height = shape.height;
}
}
class Triangle : Shape
{
public string style;
public Triangle(int x)
: base(x)
{
style = "isosceles";
}
public Triangle(Triangle triangle)
: base(triangle)
{
style = triangle.style;
}
}
class Draw
{
static void Main()
{
Triangle triangle1 = new Triangle(5);
Triangle triangle2 = new Triangle(triangle1);
}
}
Here second constructor of the Triangle receives a Triangle object and pass this to the Shape constructor which is base type. And this is an example of passing a derived class reference to a base class reference. For more about this see page 299 of
Herbert Schildt's book.

Categories

Resources