Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialEmmet Lowry
10,196 PointsProblem with inheritance Task
My code seems fine but not passing any advice im stuck for ages namespace Treehouse.CodeChallenges { class Polygon { public readonly int NumSides;
public Polygon(int numSides) : base(4);
{
NumSides = numSides;
}
class Square : Polygon
{
public readonly int SideLength;
public Square(int sideLength)
{
SideLength = sideLength;
}
}
} }
3 Answers
akak
29,445 PointsHi,
You should use base
on a constructor of derived class:
namespace Treehouse.CodeChallenges
{
class Polygon
{
public readonly int NumSides;
public Polygon(int numSides)
{
NumSides = numSides;
}
}
class Square : Polygon
{
public readonly int SideLength;
public Square(int sideLength) : base(4)
{
SideLength = sideLength;
}
}
}
Nathan Schmidt
Front End Web Development Techdegree Graduate 30,054 PointsCan you write:
public Square(int sideLength) : Polygon(4)
Or is it recommended to use the base keyword?
akak
29,445 PointsYou have to use base
. If you won't you'll get:
error CS1525: Unexpected symbol `Polygon', expecting `base' or `this'.
Emmet Lowry
10,196 Pointswhy is sidelength = SideLength
babasariffodeen
6,475 Pointsbabasariffodeen
6,475 PointsWhat is the purpose of the 'base' part? And what does he number 4 to do it? How does it then relate to the sideLength parameter?
Thank you :)
akak
29,445 Pointsakak
29,445 PointsBy using
base
you are calling the constructor of the class you're inheriting from (in that case Polygon) with 4 as number of sides.. So let's try instantiate Square:public Square mySquare = new Square(25);
After that your mySquare object will have
So you can think of
base(4)
as being a call to Polygon (the parent) likenew Polygon(4)
but not explicitly. It's done while constructing a new Square. That's the beauty of inheritance. You hardcoded that if you create Square it always a Polygon with 4 sides. User just have to enter length of side. I hope you get the gist :)Why not to add triangle? It will be a polygon with 3 sides this time