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

3
  • 1
    Put it into an initializer instead. FWIW, that's valid in C++11. Commented Dec 22, 2012 at 4:56
  • Where do I put an initialization list for an anonymous struct? Commented Dec 22, 2012 at 5:09
  • I don't think you can. The only way I know of to keep both is to use C++11. Commented Dec 22, 2012 at 5:12

1 Answer 1

8

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

Sign up to request clarification or add additional context in comments.

3 Comments

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.