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