Jens Schwarzer
Jens Schwarzer

Reputation: 2870

Class-in-class object constructor/initialization fails

I'm pretty new to C++ terminology so hopefully my title is not too off. But I'm 100% sure that someone will tell me ;)

I have this piece of code:

struct B {
  struct A {
    A() : a(0) { }
    A(int a) { this->a = a; }
    int a;
  }
    a0,    // OK
    a1(1); // NOT OK!

  B() : b(0) { }
  B(int b) { this->b = b; }
  int b;
}
  b0,    // OK
  b1(1); // OK

But gcc fails to compile and generates this output:

8:8: error: expected identifier before numeric constant
8:8: error: expected ‘,’ or ‘...’ before numeric constant
2:3: error: new types may not be defined in a return type
2:3: note: (perhaps a semicolon is missing after the definition of ‘B::A’)

If I remove 'a1(1)' object or change it to 'a1' then it compiles without problems. But then I can't make use of 'A(int a)' constructor. The similar? object 'b1' has no problems with its contructor. What's the explanation for this? Thanks :)

Upvotes: 0

Views: 216

Answers (4)

Attila
Attila

Reputation: 28802

You are not allowed to initialize a member variable within the class/struct defintion (exception: static const integral (e.g. int, short, bool) members)

In the case of b0 and b1, you are declaring (and initializing) two global variables, not member variables

Upvotes: 3

ildjarn
ildjarn

Reputation: 62995

If you're asking for the correct syntax..,

struct B {
    struct A {
        int a;

        A()      : a(0) { }
        A(int a) : a(a) { }
    } a0, a1;

    int b;

    B()      : a0(), a1(1), b(0) { }
    B(int b) : a0(), a1(1), b(b) { }
} b0, b1(1);

Upvotes: 2

Mark B
Mark B

Reputation: 96311

a0 and a1 are members of the outer struct, and just like normal attributes, you cannot initalize them inline. You'll need to initialize a0 and a1 in your B constructor initalizer lists.

Upvotes: 2

lezebulon
lezebulon

Reputation: 8014

You are mismatching objects and instances. You cannot have a pre-constructed object (an instance of A) in the definition of class B, unless it is static const, but then you wouldn't still be able to initialize it in the class declaration.

Upvotes: 3

Related Questions