how do you intialize struct members?
Printable View
how do you intialize struct members?
A struct can have constructors and functions associated with it just like a class can. Just make a constructor for the struct that assigns default values to the struct's data members. Is this what you mean or are you talking about something else?
Should output: 5 9.9Code:#include <iostream>
struct mystruct
{
int iVal;
float fVal;
mystruct() : iVal(5), fVal(9.9f) {}
};
int main()
{
mystruct item;
std::cout << item.iVal << ' ' << item.fVal << std::endl;
return 0;
}
that is excactly what I wanted to know. Thank you.
>how do you intialize struct members?
The alternative is an initialization list upon variable creation:
Code:#include <iostream>
struct mystruct {
int iVal;
float fVal;
};
int main()
{
mystruct item = { 5, 9.9 };
std::cout<< item.iVal <<' '<< item.fVal <<std::endl;
}