Was this page helpful?
Your feedback about this content is important. Let us know what you think.
Additional feedback?
1500 characters remaining
How to: Upcast with safe_cast

How to: Upcast with safe_cast

An upcast is a cast from a derived type to one of its base classes. This cast is safe and does not require an explicit cast notation. The following sample shows how to perform an upcast with and without safe_cast.

// safe_upcast.cpp
// compile with: /clr
using namespace System;
interface class A {
   void Test();
};

ref struct B : public A {
   virtual void Test() {
      Console::WriteLine("in B::Test");
   }

   void Test2() {
      Console::WriteLine("in B::Test2");
   }
};

ref struct C : public B {
   virtual void Test() override {
      Console::WriteLine("in C::Test");
   };
};

interface class I {} ;
value struct V : public I {};

int main() {
   C ^ c = gcnew C;

   // implicit upcast
   B ^ b = c;
   b->Test();
   b->Test2();

   // upcast with safe_cast
   b = nullptr;
   b = safe_cast<B^>(c);

   V ^ pv;

   // implicit upcast
   I^ i = pv;

   // upcast with safe_cast
   i = safe_cast<I^>(pv);
}

Output

in C::Test
in B::Test2

Community Additions

ADD
Show:
© 2015 Microsoft