Does a derived class can inherit the constructors of its base class?
No we cannot inherit constructor of the parent class. Only member variables and member methods can be inherited in the derived class.
Constructors are not members, so they are not inherited by subclasses, but the constructor of the superclass can be invoked from the subclass.
Here's an example to illustrate how a base class constrcutor can be invoked from derived class:
public class BaseClass
{
public BaseClass()
{
// BaseClass default constructor
}
public BaseClass(int value)
{
// BaseClass constructor with one parameter
}
}
public class DerivedClass : BaseClass
{
public DerivedClass()
{
// DerivedClass default constructor
}
public DerivedClass(int value) : base(value)
{
// DerivedClass constructor with one parameter, invoking the base class constructor
}
}