Reputation:
The fragment below is from a VC++ 2008 Express Edition. Say, I have a class with a member that is a struct. I am trying to define default values for the member variables of this class. Why this does not work?
struct Country{
unsigned chart id;
unsigned int initials;
std::string name;
};
class world{
private:
Country _country;
unsigned int _population;
public:
world(){};
world():
_country():
id('1'), initials(0), name("Spain") {};
_population(543000) {}
:
:
~world(){};
};
Upvotes: 0
Views: 1753
Reputation: 56113
There are two ways to initialize the country member data. Like this ...
struct Country{
unsigned char id;
unsigned int initials;
std::string name;
};
class world{
private:
Country _country;
public:
world()
{
_country.id = '1';
_country.initials = 0;
_country.name = "Spain";
}
~world(){};
};
... or, like this ...
struct Country{
unsigned char _id;
unsigned int _initials;
std::string _name;
Country(
unsigned char id,
unsigned int initials,
const std::string& name
)
: _id(id)
, _initials(initials)
, _name(name)
{}
};
class world{
private:
Country _country;
public:
world()
: _country('1', 0, "Spain")
{
}
~world(){};
};
Note that in the second example I find it easier to initialize the Country instance because I defined a constructor as a member of the Country struct.
Or, perhaps you want to give the Country type a default constructor:
struct Country{
unsigned char _id;
unsigned int _initials;
std::string _name;
Country()
: _id('1')
, _initials(0)
, _name("Spain")
{}
};
class world{
private:
Country _country;
public:
world()
{
}
~world(){};
};
Upvotes: 6
Reputation: 113
The structure is an aggregate type.
Since it has no constructor you cannot initialise it with normal brackets, you can however use curly braces as you would initialise an array.
Upvotes: 2