VS 2005 Managed C++ Syntax Pt. 1


I had very little experience in C++ when I sat down and tried my hand at using Managed C++ in Whidbey last fall (C++/CLI).  Documentation was a bit more sparse back then and I found a few things a little difficult to figure out.  I’ve looked again and I still can’t easily find the things I struggled with so I thought I’d list them here in the hopes they may be easier for others to find.


One thing in particular was that I couldn’t find anything on was declaring vs. defining methods/functions & properties.  Here’s a quick example of utilizing the syntax:

// MyClass.h
namespace Sample
{
   public ref class MyClass
   {
   public:
      // Property declaration:
      property System::String^ Value { System::String^ get(); void set(System::String^ value); }

      // Generic method declaration:
      generic <class MyValueType>
         where MyValueType: System::ValueType
         MyValueType GetValue(int index);
   };





// MyClass.cpp
namespace Sample
{
   // Property definitions:
   System::String^ MyClass::Value::get()
   {
      // Getter code here:
   }


   // Property definitions:
   void MyClass::Value::set(System::String^ value)
   {
      // Setter code here:
   }


   // Generic method definition:
   generic <class MyValueType>
      where MyValueType: System::ValueType
         MyValueType MyClass::GetValue(int index)
   {
      // Generic method code here:
   }


You can seperate out the getter/setter declaration if you want to have different accessibility levels for each.  Another tricky thing for me was overriding virtual properties:

namespace Sample
{
   public ref class MyBaseClass abstract
   {
   public:
      // Property declaration (using a simple property):
      virtual property System::String^ Value;
   };


   public ref class MyDerivedClass : MyBaseClass
   {
   public:
      // Property declaration:
      property System::String^ Value { virtual System::String^ get() override; virtual void set(System::String^ value) override; }
   };


That’s the current syntax (Beta2).

Comments (0)