Archived

This topic is now archived and is closed to further replies.

Karl G

Constants in Classes/Structs [C++]

Recommended Posts

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??

Share this post


Link to post
Share on other sites
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)

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
Guest Anonymous Poster
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.

Share this post


Link to post
Share on other sites