#335 – Accessing a Derived Class Using a Base Class Variable

You can use a variable whose type is a base class to reference instances of a derived class.

However, using the variable whose type is the base class, you can use it to access only members of the base class and not members of the derived class.

In the example below, we have two instances of the Terrier class, which derives from Dog.  One instance is referenced by a variable of type Terrier.  Using this variable, you have access to all members of the Terrier class.  On the other hand, the variable whose type is Dog can only reference members of the Dog class, even though the reference points to an instance of a Terrier.

            Terrier bubba = new Terrier("Bubba", 2, "Happy");
            bubba.Growl();    // Can call Terrier.Growl

            Dog jack = new Terrier("Jack", 17, "Surly");
            jack.Growl();     // ERROR: Can't call Growl method

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

2 Responses to #335 – Accessing a Derived Class Using a Base Class Variable

  1. Pingback: #344 – Hidden Base Class Member Is Invoked Based on Declared Type of Object « 2,000 Things You Should Know About C#

  2. Pingback: #356 – Hidden Base Class Property Is Used Based on Declared Type of Object « 2,000 Things You Should Know About C#

Leave a comment