Anders
Anders

Reputation: 580

Inheritance: Type vs. Value

Quick question regarding inheritance. I have a base class Baseclass and two subclasses Subclass1 and Subclass2. I have a ManualResetEvent Mre defined in Baseclass, which is used for cancellation of methods in the subclasses.

In MainForm I do:

private Baseclass _baseclass;

private void Start()
{
   if(XYZ)
   {
       var Subclass1 s1 = new Subclass1();
       _baseclass = s1;
       s1.DoCancelableWork();
    }
    else
    {
       var Subclass2 s2 = new Subclass2();
       _baseclass = s2;
       s2.DoCancelableWork();
    }
}

private void Stop()
{
    if(_baseclass != null) _baseclass.Mre.Set();
}

private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
{
    if(_baseclass != null)
    {
        if(!_baseclass.Mre.WaitOne(0)) Stop();
    }
}

Let's say the DoCancelableWork() methods run in perpetuity, until the Mre it inherits from Baseclass is set (I do not define that Mre again in the subclasses). When Stop() is run, does _baseclass.Mre now refer to the Mre used in the appropriate subclass, so DoCancelableWork() is canceled?

Upvotes: 1

Views: 111

Answers (1)

BradleyDotNET
BradleyDotNET

Reputation: 61349

Yes. Derived classes have everything the base class does (it effectively has an instance of the base class as "part" of it).

So, if you store a derived class instance in a base class reference, then do something to a base class member through that reference, the derived class is still pointing at/using it (since they are actually the same object).

To clarify your additional questions:

Subclass s = new Subclass(), andBaseclass b = new Subclass(). Is there a clear practical difference?

No. There is no difference at all in terms of functionality. By storing it as a derived type, you get access to the derived-only members and can avoid downcasting later. If you store it off as the base class, you are implying that you will only access it as the base class type later (using polymorphism to get the derived class behavior).

Let's say I just had Subclass s1 = new Subclass(), and I never did the _baseclass = s1. Would there be any way to check if the Baseclass has been instantiated (as it has, through the Subclass)?

No. There is no need to check such a thing, since the constructor semantic for derived classes always also creates the base class. It uses the default constructor when available. If its not available, your derived constructors have to explicitly invoke the desired base class one:

public DerivedClass(string someArg) : base(someArg)
{
}

Upvotes: 1

Related Questions