Classes in C++ are probably familiar to you. In recent years, Microsoft has added a new type of class to the C++ family which it calls reference classes. These special classes were designed to play nicely with other Microsoft languages such as C#, as those languages handle classes very differently than standard C++.
A reference class (or ref class) is very similar to a normal class, but it has a few small differences that set it apart.
First, let's look at a normal class and how we might use it.
{
public:
void DoSomething();
};
int main()
{
box myBox;
myBox.DoSomething();
}
This is simple enough. Let's take a look at the same class using "ref class" instead.
{
public:
void DoSomething();
};
int main()
{
box myBox;
myBox.DoSomething();
}
It appears to be pretty much the same. All we did was use "ref class" instead of "class". Simple.
Let's go back and look at a normal class again, but this time let's allocate the memory dynamically.
{
public:
void DoSomething();
};
int main()
{
box* myBox = new box;
myBox->DoSomething();
delete myBox;
}
This could have been written way better, but it's syntactically correct.
With a ref class we do something similar, but...
{
public:
void DoSomething();
};
int main()
{
box^ myBox = ref new box;
myBox->DoSomething();
//delete myBox;
}
There are three differences here.
First, instead of creating a pointer using an asterisk, we used a "hat" (^). A hat could be called a pointer to a ref class. It's a special type of pointer.
Second, we don't call delete here. We don't need to. When the pointer myBox goes out of scope, the class is automatically and completely cleaned out of memory. Convenient!
Third, we use "ref new" instead of "new".