Constants in Classes/Structs [C++]

Started by
3 comments, last by Karl G 20 years, 3 months ago
Hey everyone! Would someone please tell me why this doesn''t work the way I think it should?
struct super
{
    const bool foo;
    super( bool m ) : foo(m) {}
};

void main()
{
    super x( true );
    cout << x.foo << endl;

    super y( false );
    cout << y.foo << endl;

    getch();
} 
Firstoff, I don''t even think this code should compile, because "foo" is designated const, yet this code modifies it at runtime. Does MSVCPP 6 just completely ignore the const modifier inside of structures??
Advertisement
because you initilise the const in the initilisir list of the contructor its, valid, that s the only place you CAN initilise the const member, if you were to move that initilisation anywhere else it wouldnt work (like inside the ctor)
The non static const means const within the instance, but it may have different values for different instances. To accomplish this, you must have to set it once when constructing the instance.
main() should have an int return value, not void .
You''re not modifying the const, you''re creating a *new* const which you initialize to a different value. Add

cout << x.foo << endl;

before program exit and behold that x.foo is still true while y.foo is false.

This topic is closed to new replies.

Advertisement