Friday, January 8, 2010

Is there any reason to use a struct over an object in C++?

I'm still new to the language, but is there any reason someone would use a struct over an object? It seems like a struct is just a lesser version of an object.Is there any reason to use a struct over an object in C++?
You would only use an object when the item requires behaviours in addition to having data (attributes). No hard and fast rule but typically if you are only keeping data together you would use a struct.





This gives some more information http://csharpthegreat.blogspot.com/2009/鈥?/a>





========


Sorry on the lesser version comment - yeah, that is true. C++ objects were derived from struct definitions in C. You can think of structs as dumb objects.Is there any reason to use a struct over an object in C++?
Struct is not a ';lesser'; version of class. It's 100% identical to a class, but instead of having default private members it has default public members.





First poster is completely wrong too.





The only reason that I see for using structs is to write a C-compatible code. Note that C's structs are indeed a ';limited'; version of a class, which cannot contain member functions, constructors/destructors, access specifiers, etc... only member fields.
In C, structs cannot contain member functions. They can contain other structs or primitive data types. C does not have classes.





In C++, there are classes, which are like structs, except they can contain executable code called member functions or methods. A struct in C++ is actually a class, except for the assumptions made on the privacy level of its members, as outlined by Mr. Mehoff, so they can contain code, unlike C.





In C++, there is no reason that I can think of to use a struct. The best way would be to use the class and be explicit about the privacy level of its members, or follow the conventions used by your organization.





In C, there is every reason to use structs. It's the only thing you have to really build data structures with.





Furthermore, structs and classes are even more different in C#. C# uses the C syntax, and many containers in C# were derived from the containers in the STL. All similarity to C# ends there. In C#, structs are 'value' types whereas classes are 'reference' types. In C++, they're all values, and if you want a reference to it then by God you just make yourself a pointer and you can have it. It is your Ritchie-Straustrup-given right.
  • liquid color try
  • fragrance oil
  • No comments:

    Post a Comment