My first post so please go easy on me!
I know that there's no real difference between structs and classes in C++, but a lot of people including me use a struct or class to show intent - structs for grouping "plain old data" and classes for encapsulated data that has meaningful operations.
Now, that's fine but at what point do you start to think that something isn't just a struct anymore and should become a class?
Things I think are reasonable for structs to have:
Things I'm not so sure about, but would probably do:
I don't think structs should have:
Where do the boundaries lie???
Also, is it reasonable to have class instances as members of a struct? e.g.
class C {private: int hiddenData; public: void DoSomething();};
struct S {int a; float b; C c; };
S s; s.c.DoSomething();
Remember, I'm not on about what you CAN do with C++, I'm interested in what you SHOULD do when designing good software.
Thoughts?
Structures in C, cannot have member functions inside structures. Structures in C++ can hold member functions with member variables.
On runtime level there is no difference between structs and classes in C++ at all. So it doesn't make any performance difference whether you use struct A or class A in your code.
There is no notion of "struct" in OOP. The definition of structures depends on the language used. For example in C++ classes and structs are the same, but class members are private by defaults while struct members are public to maintain compatibility with C structs.
Structures (also called structs) are a way to group several related variables into one place. Each variable in the structure is known as a member of the structure. Unlike an array, a structure can contain many different data types (int, string, bool, etc.).
I think there are three major, coherent schools of thought:
struct
and class
interchangeably.struct
s only to represent small POD.struct
s as records.I can't make a conclusive argument for either of these strategies. I tend to follow path 2 but I also use structs for non-POD types when I see it fitting, especially for function objects (even if these may not fulfil POD requirements).
(Incidentally, the C++ FAQ lite has a pretty good definition of POD).
EDIT I didn't touch template metaprogramming techniques, such as using struct
for placeholders (type tags) or to implement metafunctions. I guess there's absolutely no controversy in these cases: since they never contain methods (or even data), always use struct
).
My personal preference is to only use structs if there's no methods at all. If I need to add a method for any reason, it's a class.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With