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

X

Xavier Roche

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

tonydee

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
 
T

Tony D

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,014
Latest member
BiancaFix3

Latest Threads

Top