0

I created a WindowsForm class in C++/CLI with one button and onClick event. I looked into the source code and saw this:

public ref class MyForm : public System::Windows::Forms::Form
{
public:
    MyForm(void)
    {
        InitializeComponent();
        //
        //TODO: Add the constructor code here
        //
    }

protected:
    /// <summary>
    /// Clean up any resources being used.
    /// </summary>
    ~MyForm()
    {
        if (components)
        {
            delete components;
        }
    }
private: System::Windows::Forms::Button^  button1;

    ...

private: System::Void onClickButton1(System::Object^  sender, System::EventArgs^  e) {
         }

}

I would like to ask: what is the meaning of the ^ operator when declaring the button (Button^ button1;) in the class?

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
Vinigas
  • 464
  • 5
  • 18
  • This isn´t C++ (only), but C++/CLI, a Microsoft derivation of C++ mixing .NET in. If you want real C++ code, you can´t use Winforms. – deviantfan Apr 25 '15 at 06:51

2 Answers2

1

^ is the Handle to Object operator:

The handle declarator (^, pronounced "hat"), modifies the type specifier to mean that the declared object should be automatically deleted when the system determines that the object is no longer accessible.

So Button^ declares a pointer to a garbage-collected Button object, which is allocated using gcnew instead of new:

The ref new aggregate keyword allocates an instance of a type that is garbage collected when the object becomes inaccessible, and that returns a handle (^) to the allocated object.

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
1

A variable that is declared with the handle declarator ^ behaves like a pointer to the object. You can use -> to access a member of that object. The CLR garbage collector mechanism determines if the object is no longer being used and can be deleted, which means that resource management becomes easier. Unlike raw pointers in C++, which you need to delete when you are done using them.

Andreas DM
  • 10,685
  • 6
  • 35
  • 62