Reputation: 331
I was trying a polymorphism example but I got the following errors in my code :
public class CPolygon
{
CPolygon() {}
public int width {get; set;}
public int height {get; set;}
public virtual int area(){ return 0; }
}
class CRectangle: CPolygon
{
public CRectangle() {} //'Lista.CPolygon.CPolygon()' is inaccessible due to its protection level
public override int area ()
{
return (width * height);
}
}
class CTriangle: CPolygon //'Lista.CPolygon.CPolygon()' is inaccessible due to its protection level
{
CTriangle() {}
public override int area ()
{
return (width * height / 2);
}
}
static void Main(string[] args)
{
CTriangle triangle= new CTriangle();
triangle.height=5;
triangle.width=6;
int area1 = triangle.area();
}
I get the error that the derived class constructors "is inaccessible due to its protection level". I have no idea why. I did another example with implicit derived constructors which worked.
abstract class Shape
{
public Shape(string name = "NoName")
{ PetName = name; }
public string PetName { get; set; }
public abstract void Draw();
}
class Circle : Shape
{
public Circle() {}
public Circle(string name) : base(name) {}
public override void Draw()
{
Console.WriteLine("Drawing {0} the Circle", PetName);
}
}
class Hexagon : Shape
{
public Hexagon() {}
public Hexagon(string name) : base(name) {}
public override void Draw()
{
Console.WriteLine("Drawing {0} the Hexagon", PetName);
}
}
This works and has almost the same code. The constructors "Circle()" , "Hexagon()" don't require any protection level this time. Any ideas?
Upvotes: 3
Views: 2128
Reputation: 758
Class CPolygon is Public but you havent defined protection levels for CRectangle and CTriangle , do you still get the error if you make the two derived classes public ?
Upvotes: 0
Reputation: 36092
C#'s default symbol visibility is private. If you don't put "public" in front of the class or function definition, it has private visibility, which means no other class can see that symbol.
Upvotes: 4
Reputation: 888047
CPolygon() {}
That's a private
constructor.
You cannot call it outside the class.
Since derived classes must always call a constructor from their base classes, you get an error.
Upvotes: 6