I am writing a small program that is supposed to create differently shaped rooms from a base of a square. The shapes are supposed to inherit from the square, which contains List of their vertices.
Room
(Parent class) code:
class Room
{
private List<Point> vertices;
private int oX;
private int oY;
private int width;
private int height;
public Room(int oX, int oY, int width, int height)
{
vertices = new List<Point>();
addVertice(new Point(oX, oY));
addVertice(new Point(oX + width, oY));
addVertice(new Point(oX, oY + height));
addVertice(new Point(oX + width, oY + height));
this.width = width;
this.height = height;
}
}
Then I inherit LShape
from Room
, but the Visual Studio says that the vertices
variable cannot be accessed due to its protection level.
Code for LShape
(child) class
class LShape: Room
{
public LShape(int oX, int oY, int width, int height, List<Point> verticesList)
{
vertices = verticesList;
}
}
According to all the tutorials I found, this should be working, even if the parent's members are private.
Can someone explain to me where my error is, or where am I misunderstanding the concepts? Also If you have any good tutorials on inheritance, I'd be thankful.
Thank you.
According to all the tutorials I found, this should be working, even if the Parent's members are private.
No, private members are only accessible within the program text of the declaring type. So if you declare LShape
as a nested type within Room
, that will work - but otherwise it won't. You'd have access to it if it were a protected
member instead, but I'd suggest keeping it private
anyway, to be honest - instead, pass the vertices up to the constructor.
Note that your LShape
constructor will need to chain to an accessible constructor in Room
, too (or another LShape
constructor, but eventually it'll have to chain up to Room
).
See more on this question at Stackoverflow