Why Don't I Get Those Keywords?
Do you ever get jealous when you're reading code in other managed languages? Code that uses keywords such as Property and Delegate and using. Have you ever wondered whether you could use those in your C++ applications? You can, but it's not always obvious how to do so. In this column, I'll show you two such keywords and the Managed C++ equivalents.
Property
Public Class Person
Public Sub New(ByVal newname As String)
pName = newname
End Sub
Private pName As System.String
Public Property Name() As String
Get
Return pName
End Get
Set(ByVal Value As String)
pName = Value
End Set
End Property
Public Sub Report()
Console.WriteLine("My name is " & Me.Name)
End Sub
End Class
Being able to hide away the "get" and the "set" behind that property keyword gives code that uses your class the best of both worlds: It looks as though they're just talking to a public variable, but you could be enforcing some business rules on a set, or storing a completely different variable than what is passed to or returned from the property. For example, it makes sense to have a property called Age but not to store anyone's age, which changes every day. Instead, you can store the birthdate and calculate the age on request, or update the birthdate if the age has changed. Yet, to consumers of your code, it feels very much as though Age is a public variable.
When you write a Managed C++ application, you can use either the properties or the hidden get and set methods, whichever you prefer. Intellisense shows them all:

Click here for a larger image.
I prefer to use the property directly:
int _tmain()
{
Contacts::Person* p = new Contacts::Person("Kate");
p->Name = "Kate Gregory";
p->Report();
return 0;
}
Using properties from C++ code is just as easy as using them from VB code, so could defining them be easy, too? Sure it could. The only catch is that you can only define properties like this on a managed type (class or struct).
Here's an example:
__gc class Building
{
private:
int sqft;
public:
Building(): sqft(0) {}
Building(int squarefeet): sqft(squarefeet) {}
__property int get_squarefeet()
{
return sqft;
}
__property void set_squarefeet(int value)
{
sqft = value;
}
};
