What are the benifits of using a value class in C++/CLI.Can the value class contain member functions?
What are Value Classes. At a fundamental level: value classes define objects which, once created, never change their value. A variable of a value type may only be changed by re-assigning to that variable.
A value struct or value class is a Windows Runtime-compatible POD ("plain old data structure"). It has a fixed size and consists of fields only; unlike a ref class, it has no properties.
Unlike class, structs in C++ are value type than reference type. It is useful if you have data that is not intended to be modified after creation of struct. C++ Structure is a collection of different data types.
A ref class can have standard C++ types, including const types, in any private , internal , or protected private members. Public ref classes that have type parameters are not permitted. User-defined generic ref classes are not permitted. A private, internal, or protected private ref class may be a template.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With