2

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

Codesmith
  • 5,779
  • 5
  • 38
  • 50

1 Answers1

7

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".

Sean Cline
  • 6,979
  • 1
  • 37
  • 50
  • 3
    I forgot about the option of aggregate initialization. Good thinking on that. However, the class vs. struct point is a bit irrelevant. You can put a constructor in a `struct` if you wish. – chris Dec 22 '12 at 05:18
  • Wow! It worked. I've never seen that syntax before. I'll have to look into it. thx. I read what you said about using classes for large structs, but I should be fine with this since my struct only has two members. – Codesmith Dec 22 '12 at 05:24
  • @chris Good point! I've edited my answer to make note of this. Personally, when I start thinking of constructors, I go straight for classes. – Sean Cline Dec 22 '12 at 05:28