RE: compile error when initializing descendant struct

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



Maybe I'm wrong, but this doesn't appear to be valid C++ to me... you're
using a construct that's normally used for array initialization - I
don't think it's valid for initializing an object (instead, use a ctor).
Object layout is not guaranteed to be the same as an "array" of the data
members (even if the members are the same datatype, except for perhaps
PODs), but even if it the same, I don't believe you can use array
initialization syntax just because the memory layout is the same.

Here's what I think you want to do:

struct A {
  int x;
};

struct B : public A {

  B( int arg_x, int arg_y ) : y( arg_y ) { x = arg_x ; }

  int y;
};

const B b( 1, 2 );

I don't have g++ working on this machine at the moment, but this at
least compiles on another C++ compiler.
Note that you could also give A a ctor that initializes x, and then
initialize the base class in the initialization list of B ctor (instead
of doing the assignment of x in the body of B's ctor).

HTH,
  Mike

-----Original Message-----
From: gcc-help-owner@xxxxxxxxxxx [mailto:gcc-help-owner@xxxxxxxxxxx] On
Behalf Of Dave Bender
Sent: Wednesday, April 09, 2008 6:07 PM
To: gcc-help@xxxxxxxxxxx
Subject: compile error when initializing descendant struct

Dear list,
  When I attempt to compile the following code (test2.cpp):


struct A {
  int x;
};

struct B : public A {
  int y;
};

const B b = {1, 2};


g++ gives the following error:

test2.cpp:9: error: scalar object 'b' requires one element in
initializer

My goal is to incorporate a large set of structs in a DSO (so that they
reside in the read only section). I don't see why this code should not
compile.

Thanks,
-Dave


[Index of Archives]     [Linux C Programming]     [Linux Kernel]     [eCos]     [Fedora Development]     [Fedora Announce]     [Autoconf]     [The DWARVES Debugging Tools]     [Yosemite Campsites]     [Yosemite News]     [Linux GCC]

  Powered by Linux