Skip to main content
GameDev.net gamedev.net
🔒 Locked

Structure Default Value?

Started by villiageidiot01 Jan 15, 2005 at 9:22 AM 2 replies 750+ views
Original Post
villiageidiot01
villiageidiot01
Is there any way to assign a default value to an item within a structure? When I try to compile this, the Dev-C++ tells me "7 C:\dev\structures.cpp ISO C++ forbids initialization of member `magic '" Any way to do this?

struct Hero
{
       char name[30];
       int hitpoints; 
       int magic = 0; 
       int speed = 4;
       int strength = 5;
} ;

Thanks, Tom
pex22
pex22
You have to do this in a function, i dont think it is legal in C since you cant have functions in structs in C, but in C++ you can.
same in classes, there are constructors and destructors.
so the default values you should insert in the constructor, like this:
struct Hero{Hero() {magic=0; speed=4; strength=5;}       char name[30];       int hitpoints;        int magic;        int speed;       int strength;} ;

Of course, you can define the constructure outside the struct definition.
like this:
Hero::Hero()
{
...
}
Note that there is no void in the constructor (same in the destructor)
The constructors are called first when you create an object (e.g. Hero alpha;)
And the destructors are called first when you destroy an object (in the end of the program it will be destroyed automatically if it is not a pointer, or ~alpha;
You can also add paramters to the constructor like any other function, but when there are no parameters: there are no () or (void).
Also note the constructors and destructors cannot return any value.
if you want it to return a value, you'll have to make some Init() function.

pex.
pex.
Zahlman
Zahlman
Quote:
Original post by pex22
You have to do this in a function, i dont think it is legal in C since you cant have functions in structs in C, but in C++ you can.
same in classes, there are constructors and destructors.
so the default values you should insert in the constructor, like this
(Etc.)


All ok as far as I can tell, but it's better to use an initializer list:
struct Hero {  Hero() : magic(0), speed(4), strength(5), hitpoints(10) {}  char name[30];  int hitpoints;   int magic;   int speed;  int strength;};


Although - even if you don't want to head in the OO direction, it's a good idea to design things so that your Hero will always have a name set, since a name is always needed and there isn't a sensible default... and you will suffer much less frustration in the long run if you use an actual textual type to represent text:

struct Hero {  Hero(std::string name) : name(name), magic(0), speed(4), strength(5), hitpoints(10) {}  std::string name;  int hitpoints;   int magic;   int speed;  int strength;};

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.