13

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

manu_dilip_shah
  • 880
  • 14
  • 32
  • 1
    It has a huge number of disadvantages. Not in the least making the C++/CLI syntax cumbersome, too many programmers use the hat improperly. But one unbeatable one, it makes code fast. Any half decent .NET book talks about them, be sure to read one. – Hans Passant Feb 16 '12 at 12:08

1 Answers1

17

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.

Botz3000
  • 39,020
  • 8
  • 103
  • 127
  • So why only ref classes can be inherited and not value classes – manu_dilip_shah Feb 14 '12 at 11:38
  • 2
    It's because ValueTypes are sealed, according to the CLI spec "to avoid dealing with the complications of value slicing". Updated my answer. – Botz3000 Feb 14 '12 at 11:46
  • 2
    "value=stack" isn't an implementation detail, it's just *wrong*. – Ben Voigt Feb 14 '12 at 15:59
  • 3
    Well, local variables can go on the stack, and if they're value typed then there would be a value type on the stack. But member variables go inside other objects, so a value type which is a member of a reference type ends up on the GC heap. Unless it ends up on the large object heap. Array elements are also stored on one of those heaps, as are captured local variables (when anonymous delegates and lambdas get involved). So the idea that value type is equivalent to storage on the stack is just wrong. – Ben Voigt Feb 15 '12 at 04:08
  • @BenVoigt I meant the storage location is an implementation detail, not "value=stack" (of course that is wrong). Updated the answer to clarify. – Botz3000 Feb 16 '12 at 11:29