Reputation: 2724
I'm having a slight issue with some inheritance.
In my base class I have the following constructor:
public Camera(string n)
{
name = n;
}
Then in my child class I have the following constructor:
public StereoCameras(string n)
{
name = n;
}
How ever, my child class complains it does not contain a constructor that takes 0 arguments. I'm fairly new to using inheritance like this, and I thought I had set up my childs constructor properly.
Is there something I'm missing?
Upvotes: 1
Views: 152
Reputation: 56
Just add a constructor without any parameter to the base class. This will solve your issue.
public Camera()
{
}
Upvotes: 0
Reputation: 223267
Your child class constructor call is equivalent to:
public StereoCameras(string n) : base()
since you have not defined any parameter less constructor in your base class, hence the error. Base class's parameter less constructor is called implicitly (if none is called using base
keyword)
See: Using Constructors (C# Programming Guide) - MSDN
In a derived class, if a base-class constructor is not called explicitly by using the base keyword, the default constructor, if there is one, is called implicitly
To come over the problem you can either declare a parameter less constructor in base class or call the defined constructor explictily like:
public StereoCameras(string n) : base(n)
Also from the same link
If a base class does not offer a default constructor, the derived class must make an explicit call to a base constructor by using base.
Upvotes: 3
Reputation: 6096
When a class is instantiated the constructor of the base-class is always invoked before the constructor of the derived class. If the base class does not contain a default constructor you must explicitly define how to call the constructor of the base class.
In your case this would be (note the base
call)
public StereoCameras(string n)
: base(n)
{
}
Upvotes: 0
Reputation: 34349
You will need to invoke the base constructor:
public StereoCameras(string n) : base(n)
{
}
Then the assignment in the derived class is redundant.
Upvotes: 7