PDA

View Full Version : enum initialization



ad5xj
11th November 2015, 18:02
I have been programming with Qt for some time now and I have come across a non-Qt code snippet that uses the following:



namespace MySpace {
class MyClass;
enum { SomeProperty = QTextFormat::UserProperty + 248 };
...
}


and is later reference by:



namespace MySpace {
MyClass::MyClass()
{
myFunction(MySpace::SomePropery, param2);
...
}


I am sure I should know what this is doing - but like a newbie ... I have no idea.

Can someone explain?

Environment:
Linux Mint 17.2
Qt Open Source 32 bit v5.5.1

stampede
11th November 2015, 19:28
enum { SomeProperty = QTextFormat::UserProperty + 248 };
This creates an enum type with single value named
SomeProperty. You can assign whatever (integer) values you like to enum values.
QTextFormat::UserProperty is another enum value defined in QTextFormat namespace. It has an integer value, so you can use it as a number in arithmetic expression.
The code above is roughly the same as


class MyClass;
static const int SomeProperty = QTextFormat::UserProperty + 248;
...
}

This
MySpace::SomePropery is how you can access the value of the enum. `ClassName` followed by double colon is a way to access the static member of a class.

ad5xj
11th November 2015, 19:44
Well I said "I am sure I should know what this is doing - but like a newbie ... I have no idea."

I get the enum has only one element and I also get that that element is using the value of (QTextFormat::UserProperty + 248) to create a user defined value;

I guess what has me puzzled is why do this at all. Wouldn't it be just as well to make a static value = QTextFormat::UserProperty + 248 in a global or modular context? What is the advantage of using the enum construct if there is only one element?

stampede
11th November 2015, 20:56
Almost none. Some old C++ compilers had no support for static const members. Using enums like this was a way around that limitation. This is known as "enum hack".