silla
silla

Reputation: 1327

Some trouble with subclass constructor

Let say I have this example:

class A : SomeAbstractClassWithProperties
{
  public A(string id, int size)
  {
    this.Name = "Name1";
    this.Something = new SomethingElse(id, size);
  }

  //...some stuff
}

class B : A
{
  public B(string id, int size)
  {
    this.Name = "Name2";
    this.Something = new SomethingElse(id, size);
  }
}

Ok this is not gonna work:

Inconsistent accessibility: base class A is less accessible than class 'B'
'A' does not contain a constructor that takes 0 arguments

But as we see the constructor of Class A and Class B are almost the same. Just this.Name is different. How could I rewrite class B? Any suggestions? Thank you

Upvotes: 0

Views: 122

Answers (3)

Kamolas81
Kamolas81

Reputation: 549

When you are creating an instance of B, since B extends from A you will have so call the constructor for A too. Since you are defining a constructor to class A, you no longer have the default parameter-less constructor, so you will have to call the constructor of A in the B constructor passing the needed parameters.

public A(string id,int size):base(param1,param2...paramX)

Upvotes: 0

alexander.antsypov
alexander.antsypov

Reputation: 308

You should add default (without parameters) constructor to class A or modify constructor of class B like this

public class B(string id, int size) : base(id, size)
  {
    this.Name = "Name2";
    this.Something = new SomethingElse(id, size);
  }

Upvotes: 0

petro.sidlovskyy
petro.sidlovskyy

Reputation: 5093

Please update your code

class B : A
{
  public class B(string id, int size) : base(id, size) 
  { 
     this.Name = "Name2";
  }
}

The case is you B constructor tries to call A() default constructor which desn't exists.

Upvotes: 3

Related Questions