-
March 11th, 2009, 02:44 PM
#1
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.
-
March 11th, 2009, 02:50 PM
#2
Re: How structs are initialized.
Provide a default constructor, e.g.,
Code:
struct Thing {
Thing() : value(123), title('a') {}
int value;
char title;
};
-
March 11th, 2009, 03:03 PM
#3
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
-
March 11th, 2009, 03:08 PM
#4
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....
-
March 11th, 2009, 04:06 PM
#5
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.
-
March 11th, 2009, 04:28 PM
#6
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.
Get Microsoft Visual C++ Express here or CodeBlocks here.
Get STLFilt here to radically improve error messages when using the STL.
Get these two can't live without C++ libraries, BOOST here and Loki here.
Check your code with the Comeau Compiler and FlexeLint for standards compliance and some subtle errors.
Always use [code] code tags [/code] to make code legible and preserve indentation.
Do not ask for help writing destructive software such as viruses, gamehacks, keyloggers and the suchlike.
-
March 11th, 2009, 04:59 PM
#7
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};
}
Tags for this Thread
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|