Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

ISO C++ forbids assignment of arrays - is there a way out ?

37 views
Skip to first unread message

Xavier Roche

unread,
Feb 1, 2010, 2:54:13 AM2/1/10
to
Hi folks,

How to assign an array in a constructor, when the array is needed in
another constructor ?

Typical case: a class "A" defined elsewhere (ie. not my code) which
takes an int&/char** as constructor:

class A {
public:
A(int & argc, char ** argv);
}

And my class B, which has A as member. A must be initialized in the
constructor ; therefore I tried the following construct:

class B {
public:
B();

protected:
A a;

private:
char progName[4]; // dummy
int argc;
char *argv[2];
}

B::B(): progName("foo"),
argc(1),
argv({progName, NULL}),
a(argc, argv)
{
}

This code is not correct (and won't compile) - as I can not initialize
the array directly. ("expected primary-expression before '{' token" --
"ISO C++ forbids assignment of arrays")

Is there a way out, or do I have to give up and use a pointer to A as
member, with proper "manual" new construct ?

Thanks in advance for any enlightenment.

tonydee

unread,
Feb 1, 2010, 3:46:43 AM2/1/10
to
On Feb 1, 4:54 pm, Xavier Roche <xro...@free.fr.NOSPAM.invalid> wrote:
> class B {
> public:
>         B();
>
> protected:
>         A a;
>
> private:
>         char progName[4];       // dummy
>         int argc;
>         char *argv[2];
>
> }
>
> B::B(): progName("foo"),
>         argc(1),
>         argv({progName, NULL}),
>         a(argc, argv)
> { }
>
> Is there a way out, or do I have to give up and use a pointer to A as
> member, with proper "manual" new construct ?

Data members are initialised in the order in which they are added to
the class - not necessarily the same order given in the initialiser
list (GNU gcc -Wall will warn). So, put "a" after the other data
members you wish you pass to a's constructor.

Then, one scrappy but easy way to do this is to use the comma operator
to evaluate some expressions, throwing away their values but
preserving their side effects:

struct B
{
B()
: a(((argv[0] = "one"), (argv[1] = "two"), (argv[2] = 0), argv))
{ }

const char* argv[2];
A a;
};

Cheers,
Tony

Tony D

unread,
Feb 1, 2010, 10:11:09 AM2/1/10
to
On Feb 1, 5:46 pm, tonydee <tony_in_da...@yahoo.co.uk> wrote:
> struct B
> {
>     B()
>       : a(((argv[0] = "one"), (argv[1] = "two"), (argv[2] = 0), argv))
>     { }
>
>     const char* argv[2];
>     A a;
> };

Hmmm... teach me to try to make the solution a little more interesting
by including an extra array element... argv[3] would work better.

Cheers, Tony

0 new messages