#754 – Downcast to a Reference to a Derived Class

If you have a variable that is a reference to a parent class, but it actually refers to an instance of a derived class, you can use a downcast operation to assign the reference to a variable whose type matches the derived class.

For example, assume that you have a Dog class and a Terrier class, which inherits from Dog.  You might have a reference to a Dog that actually refers to an instance of a Terrier.  To get at methods that are unique to Terrier, you’d downcast the Dog reference to a Terrier reference.

This type of conversion is known as a reference conversion.

            // Dog reference that points to a Terrier
            Dog d = new Terrier("Jack", Terrier.GrowlFactor.Severe);

            // Can't invoke Terrier methods via Dog reference
            //d.DoTerrierDance();   // ERROR

            // Downcast to Terrier.  Need explicit conversion
            Terrier t = (Terrier)d;

            // Can now treat like Terrier

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

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 )

Connecting to %s

%d bloggers like this: