We help IT Professionals succeed at work.

We've partnered with Certified Experts, Carl Webster and Richard Faulkner, to bring you two Citrix podcasts. Learn about 2020 trends and get answers to your biggest Citrix questions!Listen Now

x

# can I initialize member like this?

on
Medium Priority
322 Views
here is what I did:

class Date {
private:
int day;     // Stores the day, 1-31.
int month; // Stores the month, 1 -12.
int year;  // Stores the year.  Any by size of int.

// List of months for converting to a value.
char months[] = 3D { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug",
"Sep", "Oct", "Nov", "Dec"};
public:
Date();
Date(char *d);
//{  // Constructor with the string for part 2.
//  setDate(d);
//}
void setDate(const char *d);
char *getDate() const;class Date {
private:
int day;     // Stores the day, 1-31.
int month; // Stores the month, 1 -12.
int year;  // Stores the year.  Any by size of int.

// List of months for converting to a value.
char months[] = 3D { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug",
"Sep", "Oct", "Nov", "Dec"};
public:
Date(char *d);
{  // Constructor with the string for part 2.
setDate(d);
}
void setDate(const char *d);
char *getDate() const;
...
};

I got an error msg: Can't initialize a member here.
on the line of char months[] = 3D {...};

why?

Thank you
Comment
Watch Question

## View Solution Only

Commented:
What do you mean by 3D??

I think the correct way is like the following :
char months[12][4] = { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};

"Jan" is a string rather than a character.
4 instead of 3 because of a string separator.

Not the solution you were looking for? Getting a personalized solution is easy.

Commented:
I got rid of 3D and do what you gave me. I still got the error msg.

Commented:
Hardaway's answer is syntaclly right to initialize an array.  But you can't initialize an array that is a class/structure member.  (or you can, but you must do it in the constructor.)

Commented:
Actually, I think the "real" problem is that you don't want the array to be a member, or if you do, you want it to be a static member.  The way it is not, as a non-static member, each data object will have its own (private, seperate) copy of the months array.  That is probably a waste.  You can either declare it global or static.  (Static will produce one copy that is shared among all the date objects).

Commented:
Also multi-dimentional arrays in C++ are kinda weak.  I avoid them if I can.  For this kind of table, an array of character pointers usually works best.  Like

const char *Months = {"Jan","Feb",Mar"};

one advantage of this is that the strings can be different lengths, like

const char *Months = {"January","February",March"};

##### Thanks for using Experts Exchange.

• View three pieces of content (articles, solutions, posts, and videos)
• Ask the experts questions (counted toward content limit)
• Customize your dashboard and profile