const char pointer declaration in struct

Codesmith picture Codesmith · Dec 22, 2012 · Viewed 8.8k times · Source

I'm trying to do this, but my compiler won't let me:

    struct {
        const char* string = "some text";
    } myAnonymousStruct;

I believe it's because no assignments can be made in a struct declaration - they're supposed to be made in functions or otherwise. But am I really not even allowed to assign const char* variables?
If anyone can let me know what I'm missing, I'd really appreciate it. thx

Answer

Sean Cline picture Sean Cline · Dec 22, 2012

Your code is perfectly fine on compilers that support C++11 or later.

Before C++11, members of a struct could not be default initialized. Instead they must be initialized after an instance struct is created.

If it fits your needs, you could use aggregate initialization like so:

struct {
    const char* string;
} myAnonymousStruct = { "some text" };

But if you're trying to default initialize more than just the one instance of the struct then you may want to give your struct a constructor and initialize members in it instead.

struct MyStruct {
    const char* str;
    MyStruct() : str("some text") { }
};

MyStruct foo;
MyStruct bar;

In the previous example, foo and bar are different instances of MyStruct, both with str initialized to "some text".