Value Class in C++/CLI

manu_dilip_shah picture manu_dilip_shah · Feb 14, 2012 · Viewed 7.3k times · Source

What are the benifits of using a value class in C++/CLI.Can the value class contain member functions?

Answer

Botz3000 picture Botz3000 · Feb 14, 2012

a value class is a ValueType - that means, whenever you assign it to another variable of the same type, the whole object gets copied into the other variable, leaving you with two separate copies. Examples of this are basic numeric data types like int, bool or double. ValueTypes are sealed, which means you cannot derive from them.

A ref class is a reference type - if you assign it to another variable of the same type, you copy only a reference. So the two variables basically "point" to the same data.

So the main difference between value class and ref class are the copying semantics. Both can contain Methods, fields properties and so on. Also, you cannot derive from a value class.

The difference between using the class and struct keywords in this context is the default visibility of members. It is private for ref/value class and public for ref/value struct.

A common misconception is that value/ref specify the storage location (value=stack, ref=heap). The storage location of each object, whether ValueType or reference type, is an implementation detail noone should rely on or make assumptions about and it is entirely at the runtime's discretion which storage location is appropriate in any given context.