Sign in to follow this  
markrodgers11

Struct vs Classes?

Recommended Posts

markrodgers11    149
What is the difference between structs and classes in C++? Edited by jbadams
: altered the language of the post slightly to clarify the question, as a few users seemed slightly unsure.

Share this post


Link to post
Share on other sites
Waterlimon    4398
You should just google it to find a full comparison, but AFAIK members of classes are private by default while for structs they are public.

For variables at least. Not sure about differences regarding methods abd such.

Share this post


Link to post
Share on other sites
Serapth    6671
[quote name='Brother Bob' timestamp='1350931254' post='4992846']
The only difference is default member and inheritance access. Structs default to public members and inheritance while classes default to private.
[/quote]

This.

The only difference is that structs default to public while class defaults to private. This behavior of defaulting to public can be handy, such as with [url="http://en.wikipedia.org/wiki/Functor"]functors[/url], but that is a problem outside of your current paygrade.

The other key difference is, structs exist in C, classes do not.



One thing that is of extreme importance to realize is... this is true ONLY for C++. In C#, a struct is MASSIVELY different than a class and the distinction is of great importance to be aware of, and is something that catches C++->C# programmers off guard. In C#, a struct is allocated on the stack. Edited by Serapth

Share this post


Link to post
Share on other sites
KnolanCross    1974
[quote name='Serapth' timestamp='1350931978' post='4992852']
[quote name='Brother Bob' timestamp='1350931254' post='4992846']
The only difference is default member and inheritance access. Structs default to public members and inheritance while classes default to private.
[/quote]

This.

The only difference is that structs default to public while class defaults to private. This behavior of defaulting to public can be handy, such as with [url="http://en.wikipedia.org/wiki/Functor"]functors[/url], but that is a problem outside of your current paygrade.

The other key difference is, structs exist in C, classes do not.



One thing that is of extreme importance to realize is... this is true ONLY for C++. In C#, a struct is MASSIVELY different than a class and the distinction is of great importance to be aware of, and is something that catches C++->C# programmers off guard. In C#, a struct is allocated on the stack.
[/quote]

Can't say for CPP but on C a struct variable is also allocated on the stack (an struct pointer may point to a struct allocated on the stack or on the heap).

EDIT:
Just tested on CPP, also on stack. Edited by KnolanCross

Share this post


Link to post
Share on other sites
Serapth    6671
[quote name='KnolanCross' timestamp='1350935116' post='4992875']
Can't say for CPP but on C a struct variable is also allocated on the stack (an struct pointer may point to a struct allocated on the stack or on the heap).

EDIT:
Just tested on CPP, also on stack.
[/quote]

In C++ it all comes down to how it was allocated. If it was new'd, it's on the heap, otherwise it's on the stack. The same is equally true for classes.

For example:
[CODE]
MyStruct * struct = new MyStruct(); // Heap
MyStruct struct2; // Stack
[/CODE]
[quote name='Washu' timestamp='1350935363' post='4992876']
[quote name='Serapth' timestamp='1350931978' post='4992852']
In C#, a struct is allocated on the stack.
[/quote]
No. In C# a struct is a value type. Versus a reference type. The "allocated on the stack" part is merely a consequence of it being a value type and only applies to instances declared within a method or passed via parameters. Your REFERENCE to a class, within a method, is ALSO allocated on the stack.
[/quote]

True, although what I said was not false. It was however increasingly off topic. The most important take away is, the relationship between classes and structs is much more profound in C# than C++. Edited by jbadams
Fixed quote tag referencing incorrect user.

Share this post


Link to post
Share on other sites
markrodgers11    149
getting back on topic of C++, so I suppose it is just personal preference since either can be used for same thing? Is their any that is more preferred by advanced C++ programmers, to get me into good habits?

Share this post


Link to post
Share on other sites
frob    44919
[quote name='markrodgers11' timestamp='1350939462' post='4992897']
getting back on topic of C++, so I suppose it is just personal preference since either can be used for same thing? Is their any that is more preferred by advanced C++ programmers, to get me into good habits?
[/quote]
It is generally a signal of intent.

If you intend it to hold plain old data and not functions and such, call it a struct.

Share this post


Link to post
Share on other sites
Brother Bob    10344
It is entirely a personal preference which one you chose. A common way is to use [i]struct[/i] for pure data containers and [i]class[/i] for objects which has some way of interacting with them. For example, a header for a file format could be a [i]struct[/i] since its only purpose is to represent and group the data in a file, but your linked list could be a [i]class[/i] since you interact with it by adding data to it. Whatever you decide to do though, consistency is important in any design decision. Edited by Brother Bob

Share this post


Link to post
Share on other sites
KnolanCross    1974
[quote name='Serapth' timestamp='1350937544' post='4992888']

In C++ it all comes down to how it was allocated. If it was new'd, it's on the heap, otherwise it's on the stack. The same is equally true for classes.

For example:
[CODE]
MyStruct * struct = new MyStruct(); // Heap
MyStruct struct2; // Stack
[/CODE]

[/quote]

Yes, exactly as C (using malloc instead of new), but the way you said it seemed like you meant that structs would be allocated on the heap on CPP and on stack on C#.

Share this post


Link to post
Share on other sites
markrodgers11    149
Ahh I see. but what frob says brings up another question for me about structs/classes.

[quote name='frob' timestamp='1350939982' post='4992899']
If you intend it to hold plain old data and not functions and such, call it a struct.
[/quote]
so does this mean structs can not hold functions or is it just preferred to put functions in classes and plain data in structs?

Share this post


Link to post
Share on other sites
Brother Bob    10344
They can hold functions. Some people just differentiate between structs and classes if they have functions or not (what I commented on earlier; if you need to interact with them). There really is no difference other than default method and inheritance access as far as the language goes.

Share this post


Link to post
Share on other sites
SiCrane    11839
It's interesting that the convention of struct for really simple things and class for more complex things is actually in the language of the C++ standard itself. For example, most of the time the kinds of classes are just called classes (e.g. "abstract classes" or "base classes") but plain old data classes are called "POD structs" in the standard. It may just be a convention, but it's deeply embedded in the culture of C++ developers. It gets more fun in the C++11 standard when you've got two special kinds of classes: trivially copyable classes and standard layout classes, and if you've got a class that meets both criteria (and a few more on top) it's called a POD struct.

Share this post


Link to post
Share on other sites
Daaark    3553
Both are used for the same thing. To group bits of data together to represent 1 thing. Like a pixel, you have red, green, blue, and alpha components.

So a 32 bit pixel would look like this:

Struct Pixel
{
byte R;
byte G;
byte B
byte A;
}

This is just a simple structuring of data, so you can keep track of all the components that come together to represent a pixel. Everything is publicly visible, just like a C style struct. You can access all members like this:

Pixel pxExampleRed;
pxExampleRed.R = 255;
pxExampleRed.B = 0;
pxExampleRed.G = 0;
pxExampleRed.A = 255;

You have to remember to assign a value to all components of your struct, otherwise they will have whatever random value was set in memory where they were allocated.

Sometimes it's nice to fill out a structure to pass to a function, instead of having a giant function call that takes up 20 lines. Windows API programming is a lot like this. You can also use a structure as to return data from a function.

Classes are a bit more complicated. Their data tends to NOT be publicly visible. Instead of accessing their data directly, you call functions that will take your input and do something with it to the object that the class is representing. They also have constructors and destructors so they can handle their own initialization and clean up.

The intent of a struct is a simple grouping of data for convenience. A class is an more complex object that can take care of itself.

Share this post


Link to post
Share on other sites
Washu    7829
[quote name='Daaark' timestamp='1350964520' post='4992975']
Classes are a bit more complicated. Their data tends to NOT be publicly visible. Instead of accessing their data directly, you call functions that will take your input and do something with it to the object that the class is representing. They also have constructors and destructors so they can handle their own initialization and clean up.

The intent of a struct is a simple grouping of data for convenience. A class is an more complex object that can take care of itself.
[/quote]

Rather than spouting incorrect information, please note Brother Bob's reply, which is 100% correct:

[quote name='Brother Bob' timestamp='1350931254' post='4992846']
[b]The only difference is default member and inheritance access. Structs default to public members and inheritance while classes default to private.[/b]
[/quote] Edited by Washu

Share this post


Link to post
Share on other sites
kunos    2254
[quote name='Brother Bob' timestamp='1350945020' post='4992925']
They can hold functions. Some people just differentiate between structs and classes if they have functions or not
[/quote]

That's what I do, and what most companies I've worked for do. I only break the "no member functions" rule by providing my structs with an inline default constructor that initialise the thing to zero (or other meaningful values).

Share this post


Link to post
Share on other sites
mrbastard    1577
[quote name='Washu' timestamp='1350970666' ]
Rather than spouting incorrect information, please note Brother Bob's reply, which is 100% correct:
[/quote]

Once Serapth had thought to ask which language the OP was asking about, sure.... [img]http://public.gamedev.net//public/style_emoticons/default/mellow.png[/img] It's also far from a full answer, especially for the OP's apparent level of experience.

While not scrupulously correct, I suspect Daark's answer will be more useful to the OP than many of the other contributions to this thread, because it talks about how the concepts are actually used. I agree that Daark's reply contains inaccuracies, but I think it would have been much more helpful of you as a moderator to correct them point by point - thereby continuing the discussion rather than limiting it to the shortest standardese quote possible. Edited by mrbastard

Share this post


Link to post
Share on other sites
Brother Bob    10344
[quote name='mrbastard' timestamp='1350990756' post='4993056']
Once Serapth had thought to ask which language the OP was asking about, sure....
[/quote]
To be clear, the specific language [i]was[/i] given from the very beginning of the thread. Not in the most obvious place though; the thread is tagged as "C++".

Share this post


Link to post
Share on other sites
KaiserJohan    2317
[quote name='Daaark' timestamp='1350964520' post='4992975']
Both are used for the same thing. To group bits of data together to represent 1 thing. Like a pixel, you have red, green, blue, and alpha components.

So a 32 bit pixel would look like this:

Struct Pixel
{
byte R;
byte G;
byte B
byte A;
}

This is just a simple structuring of data, so you can keep track of all the components that come together to represent a pixel. Everything is publicly visible, just like a C style struct. You can access all members like this:

Pixel pxExampleRed;
pxExampleRed.R = 255;
pxExampleRed.B = 0;
pxExampleRed.G = 0;
pxExampleRed.A = 255;

You have to remember to assign a value to all components of your struct, otherwise they will have whatever random value was set in memory where they were allocated.

Sometimes it's nice to fill out a structure to pass to a function, instead of having a giant function call that takes up 20 lines. Windows API programming is a lot like this. You can also use a structure as to return data from a function.

Classes are a bit more complicated. Their data tends to NOT be publicly visible. Instead of accessing their data directly, you call functions that will take your input and do something with it to the object that the class is representing. They also have constructors and destructors so they can handle their own initialization and clean up.

The intent of a struct is a simple grouping of data for convenience. A class is an more complex object that can take care of itself.
[/quote]

Structs have constructors and destructors aswell.. they get 'random' values if you dont define them (i.e the compiler generates them), which is exactly the same for a class. Edited by KaiserJohan

Share this post


Link to post
Share on other sites
Serapth    6671
[quote name='KaiserJohan' timestamp='1350994953' post='4993069']
Structs have constructors and destructors aswell.. they get 'random' values if you dont define them (i.e the compiler generates them), which is exactly the same for a class.
[/quote]

I wouldn't say random. The default constructor is pretty well documented in the standard.

That leads to an interesting ( and yes, related... at least to KaiserJohan's comment ) trivia question ( and one of those C++ hand grenades in waiting ).

What will this program output and why?
[code]
#include <iostream>
int main(int agrc, char** argv)
{
int* meaningOfLife = new int;
int* meaningOfLife2 = new int();
std::cout << *meaningOfLife << " and " << *meaningOfLife2 << std::endl;
}
[/code] Edited by Serapth

Share this post


Link to post
Share on other sites
Serapth    6671
[quote name='Shippou' timestamp='1351000366' post='4993087']
[quote name='Serapth' timestamp='1350999819' post='4993085']
What will this program output and why?
[code]
#include <iostream>
int main(int agrc, char** argv)
{
int* meaningOfLife = new int;
int* meaningOfLife2 = new int();
std::cout << *meaningOfLife << " and " << *meaningOfLife2 << std::endl;
}
[/code]
[/quote]

[CODE]
NULL and NULL
[/CODE]
Nether pointer are pointing to anything.
[/quote]

Nope, not the answer. Here's a hint, one is a pointer to [i]something [/i]and technically neither will return null.

Share this post


Link to post
Share on other sites
Brother Bob    10344
The first one will print an undefined value since the integer allocated by [i]new int[/i] is not initialized. The second one will print zero, because the integer allocated by [i]new int()[/i] is default initialized to zero. The parentheses syntax default initializes primitive types to zero. The same goes for members; if you explicitly default initialize a primitive member of a structure or a class in the initializer list it is initialized to zero; if you omit it from the initializer list it is left with an undefined value.

Share this post


Link to post
Share on other sites
Serapth    6671
[quote name='Brother Bob' timestamp='1351003139' post='4993100']
The first one will print an undefined value since the integer allocated by [i]new int[/i] is not initialized. The second one will print zero, because the integer allocated by [i]new int()[/i] is default initialized to zero. The parentheses syntax default initializes primitive types to zero. The same goes for members; if you explicitly default initialize a primitive member of a structure or a class in the initializer list it is initialized to zero; if you omit it from the initializer list it is left with an undefined value.
[/quote]

This man gets the prize. Granted, that the prize is nothing makes winning this particular contest bittersweet at best.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this