Upcast base to derived class

In a recent project, I had a need to upcast from a base class to a derived class. Below I describe the problem and the conditions where the upcast works.

Consider that there is a method, Method1, that returns an instance of class C1.You don't have the ability to enhance C1. But, you would like to add new services to C1.

 
So you derive C2 from C1
Class C2: C1
{
    void NewFunctionality()
}
Now, examine the following code
C1 c1 = <SomeClass>.Method1();
 
// Now to use the NewFunctionalrity, have to upcast
 
C2 c2 = (C2) c1;   //will not work !
Upcasting C1 to C2 will compile but fail at runtime causing an exception, CastException. There is no way for the compiler to do this upcast as
it would mean providing the new additional features that C2 may have.
 
So why does it compile ?
 

The same upcast will succeed if base class was cast initially from a derived class. for e.g., the following
will run successfully
 
   C2 c2 = new C2();

  C1 c1 = (c1) c2;   // Downcast to base class

   C2 c21 = (C2) c1;   //The upcast will succeed

Since "c1" was downcast from the derived type C2, the upcast succeeds.
 
Hide comments

Comments

  • Allowed HTML tags: <em> <strong> <blockquote> <br> <p>

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.
Publish