#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
Advertisements

About Sean
Software developer in the Twin Cities area, passionate about .NET technologies. Equally passionate about my own personal projects related to family history and preservation of family stories and photos.

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 Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: