Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a subclass inherit a constructor?

Tags:

.net

oop

vb.net

  1. I have a base class, "B", which has two constructors, one with no paremeters and the other that accepts one param, an integer
  2. I have a subclass, "S", which inherits from "B" and does not define any constructors in it.
  3. I create an instance of S, attempting to pass to the constructor an integer.

I get the error:

Error 1 Too many arguments to 'Public Sub New()"

This surprises me because I thought that if a constructor is not defined in the subclass, S, that the base class constructor method, specifically, the one with the single integer param would be invoked w/o an error.

Do you have any idea why I am getting this error? Are constructors a special case?

like image 666
Chad Avatar asked Jan 21 '26 04:01

Chad


1 Answers

The constructor for a class only applies to the class it's defined in, even in an inheritance relationship. To be able to take advantage of your base-class 1-arg constructor, you'd have to do something like this (in C#):

public class S : B
{
    public S()
    {
        // do something for S
    }

    public S(int myInt) : base(myInt)
    {
        // do something for S
    }
}
like image 196
Andy White Avatar answered Jan 22 '26 16:01

Andy White



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!