Simple Inheritance question

R

relient

Hi, I just started the chapter on "Inheritance" and I'm a bit confused
so I have three questions: first, here's the code:

using System;
using System.Collections.Generic;
using System.Text;

namespace ConsoleProject1
{
public class Base
{
public virtual void SomeMethod( )
{
Console.WriteLine("Inside: Base.SomeMethod.");
}
}

public class Derived : Base
{
public override void SomeMethod( )
{
base.SomeMethod( );
}
}

public class MainClass
{
public static void Main( )
{
Derived d = new Derived( );
d.SomeMethod( );
}
}
}

1.)
In the above example, shouldn't Derived.SomeMethod() call itself
(infinite loop) because
I overrided the base method implimentation? meaning, Base.SomeMethod
does not "exist" anymore but only my implimentation of SomeMethod() in
the Derived class?

2.)
If I instead marked the method in the derived class with the "new"
keyword, I would have
access to two implimentations of the same method name:
Base.SomeMethod() and Derived.SomeMethod(),.. no?

3.)
When you inherit from a base class, the effect is exactly the same as
if you had explicitly declared the inherited members in your derived
class, true or false?


Thanks in advance,
relient.
 
K

Kevin Frey

1. No, the function for Base.SomeMethod still exists. When you invoke
base.SomeMethod( ) you are indeed calling the base class implementation.

2. The new method is a documentary indicator that you are replacing a base
class implementation of a method, variable, class etc with a new one. It
therefore "hides" the item in the base class. Without the modifier you will
get compiler errors. There are two different implementations of
SomeMethod( ), and calling <derived>.SomeMethod( ) will call the derived
method's implementation. The principal "gotcha" with the new modifier is if
you are using polymorphism you should be using virtual functions, not the
"new" modifier.

3. The answer depends on what perspective you are looking at the object. If
you are using inheritance purely for "implementation inheritance" then the
affect of inheritance is virtually the same as if you had manually added all
of the members of the base class to your derived class, with a couple of
small exceptions, like elements redeclared with "new".

But if you are using inheritance with the intent of using polymorphism, then
they are certainly not the same, because polymorphism needs the concept of
virtual functions associated with a base class that have differing
implementations based on the derived class.

Hope this helps.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top