Topic: FAQ? Initializing array members


Author: runeh@sofus.dhhalden.no (RUNE HALFDAN HOLST HUSEBY)
Date: Thu, 7 May 1992 23:40:47 GMT
Raw View
This may be a FAQ, but I'm new to C++ programming, and haven't been reading
this group for before

In the following code, I try to initialize an array of int's, but my
compiler (Borland C++ 3.0) tell me I 'cannot initialize a class member here'

class Name
{
 int trouble[6] = {3,6,1,7,5,8}; // creates error
public:
 .
 .
 .
}

I know it can be initialized outside if I make it static, but I don't want
to keep the changes I do to the array.

Please send any answers to:
Inet: runeh@sofus.dhhalden.no

Thanks in advance


/-------------------------------}--}--{ /----------------------------------\
| Rune Halfdan Holst Huseby      }  {  |  S-Mail: Atomveien 18             |
|  _______________________________}{   |          1750 HALDEN              |
| (_____(_runeh@sofus.dhhalden.no_)    |          NORWAY                   |
|-------------------------------------/ \----------------------------------|
| Real programmers never work 9 to 5. If any real programmers are around   |
| at 9 am, it's because they were up all night.                            |
\--------------------------------------------------------------------------/




Author: psrc@cbnewsl.cb.att.com (Paul S. R. Chisholm)
Date: Sun, 17 May 1992 03:05:29 GMT
Raw View
In article <runeh.21@sofus.dhhalden.no> runeh@sofus.dhhalden.no (RUNE HALFDAN HOLST HUSEBY) writes:
> . . . Borland C++ 3.0 tell[s] me I 'cannot initialize a class member here'

> class Name
> {
>  int trouble[6] = {3,6,1,7,5,8}; // creates error
> // ...
> }

> I know it can be initialized outside if I make it static, but I don't want
> to keep the changes I do to the array.

Okay, so every instance of the class should have a trouble[] array
initialized as you describe.  Put it in the constructor.  I don't have
the ARM or a C++ compiler handy, so I don't know if the following would
work:

Name::Name() :
 trouble( {3,6,1,7,5,8} )
{
 // ...
}

or if you have to do this:

Name::Name()
{
 trouble[0]=3; trouble[1]=6; trouble[2]=1;
 trouble[3]=7; trouble[4]=5; trouble[5]=8;
 // ...
}

If you have multiple constructors, you'll probably want a private
member function to initialize the elements of trouble[] (which gets
called by all the constructors).

Paul S. R. Chisholm, AT&T Bell Laboratories, paul.s.r.chisholm@att.com
att!pegasus!psrc, psrc@pegasus.att.com, AT&T Mail !psrchisholm
I'm not speaking for the company, I'm just speaking my mind.