0

I have a

class A  
{  
private:  
    static const int b = 10;  
public:
    static void testReadOnly(int _b)
    {
        const_cast<int &>(A::b) = _b;
    }
};  

and I want to test whether the member variable b is initialized at compile time and therefore stored in the code-segment (read-only).
To do so, I try to change the value of b, which should produce some sort of runtime error (i.e. Segmentation fault, thrown by the MMU), if it actually is stored in the code-segment.

I supposed that above code should build, but my compiler/linker tells me undefined reference to 'A::b'

Why?

user2950911
  • 873
  • 3
  • 12
  • 19
  • 5
    Attempting to change a constant variable is undefined behavior. That means that it might give a runtime error, or it might not. – Some programmer dude Nov 10 '13 at 13:54
  • it is undefined in general, as generally a const variable can be stored anywhere. but a write-operation on read-only memory should definitely produce a runtime error. – user2950911 Nov 10 '13 at 14:07

1 Answers1

2

Put a definition for the static member, outside of class declaration to solve linkage errors:

class A  
{  
    static const int b = 10;
    ...
};

const int A::b;
~~~~~~~~~~~~~~~

In addition, any modification of a constant value (by weird castings) will invoke undefined behavior.

Undefined behavior is a unknown behavior, sometimes causes to crash the application, sometimes not.

masoud
  • 55,379
  • 16
  • 141
  • 208
  • when i put a definition for b outside of the class declaration, the compiler complains about a duplicate initialization of b, as it was already initialized inside the class declaration. I agree that casting away constness and modifying the value invokes undefined behavior, but i am certain that an attempt to perform a write operation on read-only memory will produce a segmentation fault. – user2950911 Nov 10 '13 at 14:02
  • See my code again, ensure it looks like above code. Initialize it by `=10` once in the class declaration _or_ for definition of `b`. – masoud Nov 10 '13 at 14:03
  • thanks, you were right. there was a second definition (w/o initialization) missing, outside the class declaration. Now my code compiles and my program crashes as intended ;-) – user2950911 Nov 10 '13 at 14:14