initializing a variable inside a struct

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
struct birthday
{
	int month, day, year;
};

struct person
{
	char last[30];
	char first[30];
	birthday date, *dob. // (*)
} *per[3], per2[3];

int main()
{
	for (int n = 0; n < 3; ++n)
        {
		per[n] = &per2[n];
                per[n]->dob = &per2[n].date; // (**)
         }

	for ( int m = 0; m < 3; ++m)
	{
		cout << "\nEnter las, first, month, day and year (FORMAT: Smith Marry 2 3 2004 ): ";
		cin >> per[m]->last >> per[m] ->first >> per[m]->dob->month;
	}

[..............]

	
}


So I have a piece of code like the above.I attempted to change line (*) into
birthday date, *dob = &date., so that I could omit line (**).

Unfortunately, I got a bunch of errors when compiling this code. It said something like "only static const integral data members can be initialized within a class....", which doesn't make much sense to me. So the question is, why is it illegal?

Speaking of "static", does static in C++ have the same meaning as that in Java?
I mean, when I construct a class in Java, if I want a variable ( or constatn, method, whatever...) to be shared by all instances of the class, I would put "static" before the variable type. Can I do that in C++?
Last edited on
You can't declare a variable's value in the definition of a class. It's that simple.
A class isn't a piece of code that can be "executed". It's a definition of a type. Only when you create an object of that type can you then start defining variables, because only then do the variables even exist.
The sole exception is static variables. Statics are, like in java (yes that concept is the same in C++), universal to a class. Therefore, they are not quite members of that class, but just a variable bound to all objects of that class. Therefore, because they will be the same no matter the object in question, I believe they may be declared in class, assuming that, as noted by your compiler, constant integral types.
Last edited on
Topic archived. No new replies allowed.