May 05, 2008 Archives

2008-05-05

a fellow sufferer

defective C++

Thank you, Andreas


Posted by Alexander Bernauer | Permanent Link | Categories: C++

2008-05-05

tell me why!

Most C++ quirks can be argued by efficency or inheritence reasons. But sometimes I just don't see why there is yet another exception in the rules of the language. Such an example is the initialization of static constant data members:

Section 9.4.4 of the ISO standard says:

If a static data member is of const integral or const enumeration type, its declaration in the class definition can specify a constant-initializer which shall be an integral constant expression.

Here is an example of this:

class X {
    static const int i = 23;
};

Now, I wonder why this in-place initialization is restricted to those two types. I would like to be a able to express:

class A;
class X {
public:
    static const A* special_meaning=0;
    void do_something(const A* with=special_meaning);
};
C++ prevents me from writing descriptive code in this case. And for what reason? I can't see any.

By the way, section 9.4.4 adds:

The member shall still be defined in a namespace scope if it is used in the program and the namespace scope definition shall not contain an initializer.
Sure, linker and such... So what is this in-place initialization good for after all?

Thank you, Liesa


Posted by Alexander Bernauer | Permanent Link | Categories: C++

2008-05-05

scope jumble

What's the value of X::i?

int g() { return 23;}
struct X {
    static int g() { return 42; }
    static int i;
};
int X::i = g();

The answer is: 42 - says ISO C++ in section 9.4.2. The initialization of the static data member is implicit in the scope of the struct. Oh, yes! The standard's example is even more fun:

int g();
struct X {
        static int g();
};
struct Y : X {
        static int i;
};
int Y::i = g();         // equivalent to Y::g();
Note that X could be definied in another header file than g and that the initialization normaly is in a cc-file. Find, Rover, find!

Thank you, Roker


Posted by Alexander Bernauer | Permanent Link | Categories: C++