Where to use union, class and struct? - c++

The classes and structs have one difference between them (as far as I know), that the struct defaults to public and class defaults to private. And then I came to know that there is a similar kind of data type which is also used in a similar manner, that is union. The union can not be used as a base class in inheritance (i don't know what that means, but I still accept it).
I wanted to know whether there are some particular instances, where struct/ union/ class, or they can be used interchangeably (except for the cases I enlisted)? Please do tell me if I am wrong somewhere.
Regards

My use of class, struct and union is the following:
class for objects that have behaviour.
struct for passive data.
union for very special cases where different data requires to be accessed as different types.
I've read this (except the union point) in the Google C++ Style guide a long time ago and I was following it since then.
Using structs to carry passive data (objects without behaviour attached to the object) have the advantage of default publicness of the members, so they can be accessed without Getters and Setters. If some member data needs to be checked/modified before assign or some member data needs to be computed/modified before be getted, IMHO they need a Setter/Getter pair and the object is a class instead of a struct.
For the union type, I find it useful for some kind of data structures that requires some weird access to the members, or needs some members to be treated as another type in some contexts. For example a 3D vector or a IP address:
union 3DVector
{
double x, y, z;
double vector[3];
} v;
// Acess members with name
v.x = 6.0; v.y = 7.0; v.z = 8.0;
// Acess members as a vector
Normalize(v.vector);
union IPAddress
{
int binary;
char octet[4];
} ip;
// Acess the binary address
std::cout << std::hex << ip.binary << '\n';
// Print in a human-readable form
std::cout << static_cast<int>(ip.octet[0]) << '.'
<< static_cast<int>(ip.octet[1]) << '.'
<< static_cast<int>(ip.octet[2]) << '.'
<< static_cast<int>(ip.octet[3]) << '\n';
The above functionality could be achieved overloading operators and conversion operators, but the union approach looks neat for me.
The unions can also be templated and can have constructor/destructor, this could be useful for serialization purposes (not for all kind of objects):
template <typename T> union Serializer
{
Serializer(const T &o) : object(o) {}
T object;
char binary[sizeof(T)];
};
SomePODObject obj; // Only POD objects please!
Serializer s(obj);
SendBuffer(s.binary);

A union and a class or structure are completely different. A union is several things at the same time, say it can be both a character array and an integer, while a class or structure is one and only one thing that encapsulates some logically connected information, as well as optionally some logic for manipulating it. The use cases for unions and the other two are quite different.
I usually use a structure when I only store some data, while if I also need some logic associated with it(i.e. I need to add methods) I use a class.

I never use union. If you end up looking at this, you better try boost variant. The only acceptable situation where we can use this is when we really need to have a deep control over the content, like custom serialization. But I would run out of this in many cases.
Also, structure are used for storing only data. If you need to add any function/method, convert it into a class.

There are some areas where I may use a struct over a class:
If I want to define an interface type that contains only pure virtual methods. This aligns with the notion that struct defaults to public.
Pure data-only types, where there is no behavior attached to the type.
Policy or trait types, as a matter a personal preference.
The union is neither a class or a struct. I only used them in C to create discriminated or variant types at a time when memory was a premium. In C++, I don't see much of an advantage in typical applications, but may still be used in embedded or low-memory applications.

Typically structs and unions are used together in C when one is accessing registers. A struct can define each bit and allow for each bit in the register to be set individually. A union will allow all the bits to be changed or accessed at the same time.
Even in C++ one needs a way to setup the hardware and write to the registers of the chip.

Related

c++ struct OO vs class OO [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
What are the differences between struct and class in C++
class and struct in c++
It looks like that struct can has constructor and destructor and members, and looks very simple, so can we use struct instead class, if not, when shall we use struct with functions when shall we use class ?
https://github.com/developmentseed/node-sqlite3/blob/master/src/database.h#L32
struct Baton {
uv_work_t request;
Database* db;
Persistent<Function> callback;
int status;
std::string message;
Baton(Database* db_, Handle<Function> cb_) :
db(db_), status(SQLITE_OK) {
db->Ref();
uv_ref(uv_default_loop());
request.data = this;
callback = Persistent<Function>::New(cb_);
}
virtual ~Baton() {
db->Unref();
uv_unref(uv_default_loop());
callback.Dispose();
}
};
struct OpenBaton : Baton {
std::string filename;
int mode;
OpenBaton(Database* db_, Handle<Function> cb_, const char* filename_, int mode_) :
Baton(db_, cb_), filename(filename_), mode(mode_) {}
};
There's absolutely no technical reason to prefer one over the other, but I've noticed a certain convention regarding the use of class or struct.
If your datatype is something that is meant to be used by other parts of your program (ie. it's part of the 'interface'), then usually people make it a class to indicate its importance. If the datatype is used only in the implementation of a function or a class and it is not visible outside of a certain scope, then make it a struct.
These are some very rought guidelines, but no one will complain if you don't follow them.
Edit: In C++ there's no real difference between the two, but other newer languages that are inspired by C++ have actually made struct and class different. In C# and in D, for example, class and struct are both used to define datatypes, but they are not the same: struct is implemented such that it should be used for 'small' types.
The only difference is the default access-level (private for a class, public for a struct). Other than that, they are completely interchangeable. You should decide which one you like better, and use that all the time (consistency makes your code more readable).
when shall we use struct with functions when shall we use class ?
It is completely your choice.
There is nothing that one can do with classes and not with structures in C++.
Only difference between structure and class are:
access specifier defaults to private for class and public for struct
inheritance defaults to private for class and public for struct
So just use the one of your choice and stick to using it consistently, do not mix classes and structures.
While as stated by other struct & class does not have any difference besides default access level. However, it's common practice to use structs mostly for data aggregation, as that is what structs are reduced to in C. For example user defined PODs are almost always created as structs in my experience.
The only difference between class and struct is the default accessibility to its members and base classes. For struct, it is public and for class, it is private.
As others have said, the main difference is the default access level of member data and functions, namely private for class and public for structs. The same goes for default inheritance access levels: private for classes and public for structs.
As for when to use which, that is a matter of what is normal for the company to do. In my experience, most companies, and indeed individuals, use structs to hold packets of pure data and classes for storing a collection of functions that operate on its own data and/or structs.
This method is a throwback to C programming where structs can only store data and not functions and so most people like to stick to this definition in C++ too.
Note that it is common to use structs for functors, which would seem to break consistency through the code of structs not containing functions, but since functors usually only overload the () operator we retain some form of consistency anyway. Plus, it saves us having to type public for one function and/or inherited structures... Oh the typing we allow ourselves to avoid ;)
A class is a reference type. When an object of the class is created, the variable to which the object is assigned holds only a reference to that memory. When the object reference is assigned to a new variable, the new variable refers to the original object. Changes made through one variable are reflected in the other variable because they both refer to the same data.
A struct is a value type. When a struct is created, the variable to which the struct is assigned holds the struct's actual data. When the struct is assigned to a new variable, it is copied. The new variable and the original variable therefore contain two separate copies of the same data. Changes made to one copy do not affect the other copy.
In general, classes are used to model more complex behavior, or data that is intended to be modified after a class object is created. Structs are best suited for small data structures that contain primarily data that is not intended to be modified after the struct is created.

Dynamic structures in C++

I am running a simulation in which I have objects of a class which use different models. These models are randomly selected for some objects of the class and specifically decided for some objects too. These objects communicate with each other for which I am using structures (aka struct) in C++ which has some
standard variables and
some additional variables which depends on models which the objects communicating with each other have.
So, how can I do this?
Thanks in advance.
You can hack around with:
the preprocessor;
template meta-programming;
inheritance/polymorphism.
Each gives a different way of producing a different user-defined type, based on different kinds of conditions.
Without knowing what you're trying to accomplish, this is the best I can do.
All instances of a structure or class have the same structure. Luckily, there are some tricks that can be used to 'simulate' what you try to do.
The first trick (which can also be used in C), is to use a union, e.g.:
struct MyStruct
{
int field1;
char field2;
int type;
union
{
int field3a;
char field3b;
double field3c;
} field3;
};
In a union, all members take up the same space in memory. As a programmer you have to be careful. You can only get out of the union what you put in. If you initialize one member of a union, but you read another member, you will probable get garbage (unless you want to do some low-level hacks, but don't do this unless you are very experienced).
Unions often come together with another field (outside the union) that indicates which member is actually used in the union. You could consider this your 'condition'.
A second trick is use the 'state' pattern (see http://en.wikipedia.org/wiki/State_pattern). From the outside world, the context class looks always the same, but internally, the different states can contain different kinds of information.
A somewhat simplified approach for state is to use simple inheritance, and to use dynamic casts. Depending on your 'condition', use a different subclass, and perform a dynamic cast to get the specific information.
E.g., suppose that we have a Country class. Some countries have a president, others have a king, others have an emperor. You could something like this:
class Country
{
...
};
class Republic : public Country
{
public:
const string &getPresident() const;
const string &getVicePresident() const;
};
class Monarchy : public Country
{
public:
const string &getKing() const;
const string &getQueen() const;
};
In your application you could work with pointers to Country, and do a dynamic cast to Republic or Monarchy where the president or king is needed.
This example can be easily transformed into one using the 'state' pattern, but I leave this as an exercise for you.
Personally, I would go for the state pattern. I'm not a big fan of dynamic casts and they always seem to be kind-of-hack for me.
If it's at compile-time, a simple #ifdef or template specialization will serve this purpose just fine. If it's at run-time and you need value semantics, you can use a boost::optional<my_struct_of_optional_members>, and if you're fine with reference semantics, inheritance will solve the problem at hand.
A union and that kind of dirty trick is not necessary.
There are several common approaches for "dynamic" attributes/properties in languages, and a few that tend to work well in C++.
For example, you can make a C++ class called "MyProperties" that has a sparse set of values, and your MyStructureClass would have its well-known members, plus a single MyProperties instance which may have zero-or-more values.
Similarly, languages like Python and Perl make extensive use of Associative Arrays/Dictionaries/Hashes to achieve this: The (string) key uniquely identifies the value. In C++, you can index your MyProperties class with a string or any type you want (after overloading the operator[]()), and the value can be a string, a MyVariant, or any other pointer-or-type that you want to inspect. The values are dynamically added to the parent container as they are assigned (e.g., the class "remembers" the last value it is given, uniquely identified by key).
Finally, in the "olden days", what you describe was commonly done for distributed application processing: You defined a C-struct with "well-known" (typed) fields/members, and the last field was a char* member. Then, that char* member would identify the start of a serialized stream of bytes that were also part of that struct (you merely serialized that array of chars when you marshalled the struct across systems). In the context of C++, you could similarly extract your values dynamically from that char* stream buffer on-access-demand (which logically should be "owned" by the class). This worked for marshalling across systems because the size of the struct was the size of everything (including the last char* member), but the "allocation" for that struct was much larger (e.g., the size of the struct itself, which was logically a "header", plus a certain number of bytes after that header, which represented the "payload" and which was indexed by the last member, the char* member.) Thus, it was a contiguous-block-of-memory struct, with dynamic size. (This would also work in C++ as long as you passed-by-reference, and never by value.)
embed an union into your structure, and use a flag to tell which part of the union is valid.
enum struct_type
{
cool,
fine,
bad
};
struct demo
{
struct_type type;
union
{
struct
{
double cool_factor;
} cool_part;
struct
{
int fineness;
} fine_part;
struct
{
char *bad_stuff;
} bad_part;
};
struct
{
int life_is_cool;
} common_part;
};
The pure and simple C++ answer is: use classes.
I can't determine from your question what you are trying to achieve: runtime variation or compile time variation, but either way, I doubt you'll get a workable implementation any other way. (Template metaprogramming aside... which isn't for the faint of heart.)

C++: When should I use structs instead of classes and where are the speed differences?

When should I use a struct instead of a class? I'm currently using classes for everything from OpenGL texture wrappers to bitmap fonts.
Is a class that I use just like a struct (no making usage of inheritance, polymorphism, etc.) still slower than a struct?
Structs and classes in C++ as you may know differ solely by their default access level (and default accessibility of their bases: public for struct, private for class).
Some developers, including myself prefer to use structs for POD-types, that is, with C-style structs, with no virtual functions, bases etc. Structs should not have behavior - they are just a comglomerate of data put into one object.
But that is naturally a matter of style, and obviously neither is slower
1) There is no real difference between the 2 other than the fact that struct members are, by default, public where classes are private.
2) No its EXACTLY the same.
Edit: Bear in mind you can use virtual inheritance with structs. They are THAT identical :)
Instead of cheaping out and referring to other questions, I'll re-iterate what others have said before I add on to them.
struct and class are identical in C++, the only exception being that struct has a default access of public, and class has a default access of private. Performance and language feature support are identical.
Idiomatically, though, struct is mostly used for "dumb" classes (plain-old-data). class is used more to embody a true class.
In addition, I've also used struct for locally defined function objects, such as:
struct something
{
something() : count(0) { }
void operator()(int value) { std::cout << value << "-" << count++ << "\n"; }
int count;
} doSomething;
std::vector<int> values;
...
std::foreach(values.begin(); values.end(); doSomething);
as others have explained, they're the same thing except for default access levels.
the only reason why classes can be perceived to be slower is because a good style (but not the only one) is the one mentioned by ArmenTsirunyan: struct for POD types, class for full-fledged object classes. The latter ones usually include inheritance and virtual methods, hence vtables, which are slightly slower to call than straight functions.
I like to use classes when I need to have an explicit destructor. Because then, you should be following the rule of three, in which case you need to write a copy constructer and assignment overloader. With all of this, it seems more natural to use a class than a struct.

Why would I use a struct in a program?

I see lot of struct code like below
struct codDrives {
WCHAR letter;
WCHAR volume[100];
} Drives[26];
We can use variables or array something like that to store the data.
But I am not sure why would I use a struct in the programs?
Structs are inherited from C, and in C++ they are almost identical to classes. The difference is that the members of a struct are by default public, while class members are by default private.
So the typical use of structs in C++ is dummy data structures which contain no logic (only - possibly - constructors and/or necessary operators).
On a more general level, classes / structs are used to group together conceptionally related data pieces. E.g. for representing a person, you may need his/her first name, surname, gender, date of birth etc. It is convenient to define a struct containing all these pieces of data as members. Then you can store and pass around instances of this struct instead of a whole bunch of distinct variables. This makes the code cleaner, less error prone, more readable and easier to maintain.
Here's some info on structs:
http://www.cplusplus.com/doc/tutorial/structures/
Also, they are useful for example returning multiple values in a function, say you need to return 3 values from a function, you can return a struct with all the 3 values inside it.
One reason to use structs might be to control the size and layout of the data so it can be written to and read from disk more easily.
Another reason would be for code that is used in C programs as well as C++
Structs can also contain methods (constructors are very useful for example). Another thing is, that with structs or classes you can define copy constructors or assignment operators which then allow you to easily copy instances of your struct, even if there are pointers inside - you take care of this in the methods of the struct and don't have to worry about it later. Moreover, this allows for a nice OOP design. There are much more benefits (but also drawbacks)...

C/C++ Struct vs Class

After finishing my C++ class it seemed to me the structs/classes are virtually identical except with a few minor differences.
I've never programmed in C before; but I do know that it has structs. In C is it possible to inherit other structs and set a modifier of public/private?
If you can do this in regular C why in the world do we need C++? What makes classes different from a struct?
In C++, structs and classes are pretty much the same; the only difference is that where access modifiers (for member variables, methods, and base classes) in classes default to private, access modifiers in structs default to public.
However, in C, a struct is just an aggregate collection of (public) data, and has no other class-like features: no methods, no constructor, no base classes, etc. Although C++ inherited the keyword, it extended the semantics. (This, however, is why things default to public in structs—a struct written like a C struct behaves like one.)
While it's possible to fake some OOP in C—for instance, defining functions which all take a pointer to a struct as their first parameter, or occasionally coercing structs with the same first few fields to be "sub/superclasses"—it's always sort of bolted on, and isn't really part of the language.
Other that the differences in the default access (public/private), there is no difference.
However, some shops that code in C and C++ will use "class/struct" to indicate that which can be used in C and C++ (struct) and which are C++ only (class). In other words, in this style all structs must work with C and C++. This is kind of why there was a difference in the first place long ago, back when C++ was still known as "C with Classes."
Note that C unions work with C++, but not the other way around. For example
union WorksWithCppOnly{
WorksWithCppOnly():a(0){}
friend class FloatAccessor;
int a;
private:
float b;
};
And likewise
typedef union friend{
int a;
float b;
} class;
only works in C
I'm going to add to the existing answers because modern C++ is now a thing and official Core Guidelines have been created to help with questions such as these.
Here's a relevant section from the guidelines:
C.2: Use class if the class has an invariant; use struct if the data members can vary independently
An invariant is a logical condition for the members of an object that a constructor must establish for the public member functions to assume. After the invariant is established (typically by a constructor) every member function can be called for the object. An invariant can be stated informally (e.g., in a comment) or more formally using Expects.
If all data members can vary independently of each other, no invariant is possible.
If a class has any private data, a user cannot completely initialize an object without the use of a constructor. Hence, the class definer will provide a constructor and must specify its meaning. This effectively means the definer need to define an invariant.
Enforcement
Look for structs with all data private and classes with public members.
The code examples given:
struct Pair { // the members can vary independently
string name;
int volume;
};
// but
class Date {
public:
// validate that {yy, mm, dd} is a valid date and initialize
Date(int yy, Month mm, char dd);
// ...
private:
int y;
Month m;
char d; // day
};
Classes work well for members that are, for example, derived from each other or interrelated. They can also help with sanity checking upon instantiation. Structs work well for having "bags of data", where nothing special is really going on but the members logically make sense being grouped together.
From this, it makes sense that classes exist to support encapsulation and other related coding concepts, that structs are simply not very useful for.
It's not possible to define member functions or derive structs from each other in C.
Also, C++ is not only C + "derive structs". Templates, references, user defined namespaces and operator overloading all do not exist in C.
One more difference in C++, when you inherit a class from struct without any access specifier, it become public inheritance where as in case of class it's private inheritance.
C++ uses structs primarily for 1) backwards compatibility with C and 2) POD types. C structs do not have methods, inheritance or visibility.
Since nobody has mentioned it yet, there is actually another difference besides the default visibility. It turns out that class and struct are actually different things in MSVC.
class Vector2;
struct Vector2 {
double x;
double y;
};
This is 1 symbol on most compilers, but 2 different symbols on MSVC. Just this code by itself does compile fine. However, if you try to use it in more complex scenarios you will run into errors where this does not compile on MSVC because it gets confused about the symbols.