Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Literal field versus constant variable in C++/CLI

Tags:

c++-cli

I'm going over some C++/CLI material and I've come across the concept of a literal field:

literal int inchesPerFoot = 12;

Is this preferable to a const because a const FIELD can't exist because a field cannot initialize itself...so:

class aClass
{
    private:
        const int aConstant = 1;    // Syntax error.
...
};

Thanks,

Scott

like image 903
Scott Davies Avatar asked Mar 08 '11 20:03

Scott Davies


1 Answers

A literal field is used for compile-time constants. It is associated with the class (similar to a "static const" field). In your example aConstant is a non-static const (an instance based) field--which is why you can't initialize it at the time of declaration (it would be initialized in the ctor's initialization list).

The difference between literal and static const fields is that referencing assemblies cannot use static const fields as compile-time constants, while literals can. However, within the same assembly, static const can be used as compile time constants.

FYI, literal is equivalent to C#'s const. initonly is equivalent to C#'s readonly.

like image 113
Matt Smith Avatar answered Sep 22 '22 22:09

Matt Smith