Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Base Class Doesn't Contain Parameterless Constructor?

Tags:

c#

constructor

I'm making my constructors a bit more strict by removing some of my empty constructors. I'm pretty new to inheritance, and was perplexed with the error that I got: Base Class Doesn't Contain Parameterless Constructor. How can I make A2 inherit from A without there being an empty constructor in A. Also, for my own personal understanding, why is A2 requiring an empty constructor for A?

Class A{     //No empty constructor for A     //Blah blah blah... }  Class A2 : A{     //The error appears here } 
like image 953
sooprise Avatar asked Oct 07 '11 15:10

sooprise


People also ask

What is a Parameterless constructor?

A constructor that takes no parameters is called a parameterless constructor. Parameterless constructors are invoked whenever an object is instantiated by using the new operator and no arguments are provided to new . For more information, see Instance Constructors.

Which constructor is called first in C#?

In C# terms, the base constructor is executed first.

What is a constructor in C sharp?

A constructor in C# is a member of a class. It is a method in the class which gets executed when a class object is created. Usually we put the initialization code in the constructor. The name of the constructor is always is the same name as the class. A C# constructor can be public or private.

What is constructor in C# with example?

In C#, a constructor is called when we try to create an object of a class. For example, Car car1 = new Car();


2 Answers

In class A2, you need to make sure that all your constructors call the base class constructor with parameters.

Otherwise, the compiler will assume you want to use the parameterless base class constructor to construct the A object on which your A2 object is based.

Example:

class A {     public A(int x, int y)     {         // do something     } }  class A2 : A {     public A2() : base(1, 5)     {         // do something     }      public A2(int x, int y) : base(x, y)     {         // do something     }      // This would not compile:     public A2(int x, int y)     {         // the compiler will look for a constructor A(), which doesn't exist     } } 
like image 127
Platinum Azure Avatar answered Oct 11 '22 08:10

Platinum Azure


Example:

class A2 : A {    A2() : base(0)    {    } }  class A {     A(int something)     {         ...     } } 
like image 29
Joe Avatar answered Oct 11 '22 09:10

Joe