Original Post
What is the difference between structs and classes in C++?
The only difference is default member and inheritance access. Structs default to public members and inheritance while classes default to private.
[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.
In C#, a struct is allocated on the stack.
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.
MyStruct * struct = new MyStruct(); // Heap
MyStruct struct2; // Stack
[quote name='Serapth' timestamp='1350931978' post='4992852']
In C#, a struct is allocated on the stack.
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?
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:
MyStruct * struct = new MyStruct(); // Heap
MyStruct struct2; // Stack
If you intend it to hold plain old data and not functions and such, call it a struct.
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.
The only difference is default member and inheritance access. Structs default to public members and inheritance while classes default to private.
They can hold functions. Some people just differentiate between structs and classes if they have functions or not
Rather than spouting incorrect information, please note Brother Bob's reply, which is 100% correct:
Once Serapth had thought to ask which language the OP was asking about, sure....
This topic has been locked by a moderator. New replies are not allowed.
With your permission, GameDev.net uses analytics cookies to understand how people use the platform. You can accept analytics or continue with necessary cookies only. Learn more