How structs are initialized.
I have a struct.
Code:
struct Thing{
int value;
char title;
}
Is there a way i can make default values for the struct. So when I make one of the structures they initialize to the default values.
Code:
Thing myThing;
cout<< myThing.value<<endl;
So when i cout the value member it would print a default value.
Re: How structs are initialized.
Provide a default constructor, e.g.,
Code:
struct Thing {
Thing() : value(123), title('a') {}
int value;
char title;
};
Re: How structs are initialized.
Excellent. This is exactly what i was looking for. My reference book does not mention the constructor use at all. Thanks
Re: How structs are initialized.
Then either it's a "C" book, or it's one of those that finds it convenient to treat structs and classes differently even though they're almost the same thing. I guarantee it'll talk about constructors when you get to classes....
Re: How structs are initialized.
The book is a C++ book. Although it does talk about constructor use in classes they are not mentioned in the "structured data" chapter which is where structs are introduced. I found it very weird that the book did not mention anything about setting "default" values for structs. So i had to ask about it.
Re: How structs are initialized.
structs and classes are essentially the same thing. The only difference between them is default member/inheritance is public for structs and private for classes.
Code:
class A {};
class B : A // private inheritance
{
int b; // private
};
struct C {};
struct D : C // public inheritance
{
int d; // public
};
Other than that there is afaik no differences between structs and classes.
Re: How structs are initialized.
FYI, for plain-old-data types at least (not sure about others), you can do something like
Code:
struct mystruct
{
const char *str;
int i;
double d;
};
int main()
{
mystruct s = {"hello", 5, 10.0};
}