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 trial

C# C# Objects Inheritance Custom Exceptions

douglas gray
douglas gray
888 Points

If a subclass inherits all of the methods and attributes of it's parent class, why is it necessary to rewrite them ?

In this example, Jeremy defines a TreehouseDefenseException class and an OutOfBounds subclass. If the subclass inherits from it's parent class why must we rewrite the constructor methods in exactly the same way, except for exchanging "TreehouseDefenseException" for "OutOFBounds"

1 Answer

Steven Parker
Steven Parker
231,269 Points

:point_right: Constructor methods are not inherited.

They can't be, because the constructor method name must be the same as the class name.

They can, however, be called implicitly, but not if you need to pass them parameters. That's what base is all about.

So can I put it like this: When we pass no arguments in the method, it's a constructor, and by default, a constructor inherits all the methods from the base class. But when we need to pass in arguments in the constructor, it doesn't remain a constructor anymore, it becomes a method. And to make this constructor inherit the functionality of the base class we need to use the base keyword. Am I getting it right?

// so as an example,

using System;
namespace TheNameSpaceGoesHere
{
  class Something
  {
    public ConstructorFunction()
    {
    }

    public ConstructorFunction(string message) : base(message) 
     //this needs to use the base keyword to inherit the functionality of the ConstructorFunction()
    {
    }
  }
}

So is the example right? :smile:

Steven Parker
Steven Parker
231,269 Points

Not quite:

  • a constructor is always a constructor because of its name and having no return type
  • the class inherits the methods of the base class
  • a class always inherits the methods of its base
  • a call to "base" is only to pass arguments to base constructor

Ans your example doesn't make sense because it's calling the base but it doesn't have one. Perhaps you meant to declare it like this:

  class Something : OtherThing

Yes, Steven Parker. You're right, actually, I couldn't get a lot of things, so messed up with the example.

And now I can understand what you're saying. Thank you.