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.)
Related
let's say I have a Union like this :
union checkUnion{
std::string* str;
bool someBool;
int aNumber;
};
How can I check which of these 3 items has been chosen during the program? I want to do individual if-queries for each of the items.
e.g.: [Pseudo-Code]
if (checkUnion == string)
{
//CODE
}
if (checkUnion == bool)
{
//DIFFERENT CODE
}
You can't. You either need to know beforehand the initialized value, or add the union to some larger struct. See this other SO question.
Update:
Unions on C++ are just for compatibility with C code, and you'd rarely need them. Even if you are creating some fancy network protocol you'd use a tool like google-protobuf than a hand-crafted union. The original objective on unions was to overlap bytes on different fields or structures, to save as many bytes as possible on those data structures while retaining compiler support.
On C++ you'd beter create a class hierarchy, and each variant as a subclass of a base class. Internally you will also have a discriminator, the C++ vtable, but the discrimination is handled by the compiler. Which is better maintainable and less error prone than hand crafted unions.
I have tried to read carefully all the advice given in the C++FAQ on this subject. I have implemented my system according to item 36.8 and now after few months (with a lot of data serialized), I want to make changes in both public interface of some of the classes and the inheritance structure itself.
class Base
{
public:
Vector field1() const;
Vector field2() const;
Vector field3() const;
std::string name() const {return "Base";}
};
class Derived : public Base
{
public:
std::string name() const {return "Derived";}
};
I would like to know how to make changes such as:
Split Derived into Derived1 and Derived2, while mapping the original Derived into Derived1 for existing data.
Split Base::field1() into Base::field1a() and Base::field1b() while mapping field1 to field1a and having field1b empty for existing data.
I will have to
deserialize all the gigabytes of my old data
convert them to the new inheritance structure
reserialize them in a new and more flexible way.
I would like to know how to make the serialization more flexible, so that when I decide to make some change in the future, I would not be facing conversion hell like now.
I thought of making a system that would use numbers instead of names to serialize my objects. That is for example Base = 1, Derived1 = 2, ... and a separate number-to-name system that would convert numbers to names, so that when I want to change the name of some class, I would do it only in this separate number-to-name system, without changing the data.
The problems with this approach are:
The system would be brittle. That is changing anything in the number-to-name system would possibly change the meaning of gigabytes of data.
The serialized data would lose some of its human readability, since in the serialized data, there would be numbers instead of names.
I am sorry for putting so many issues into one question, but I am inexperienced at programming and the problem I am facing seems so overwhelming that I just do not know where to start.
Any general materials, tutorials, idioms or literature on flexible serialization is most welcomed!
It's probably a bit late for that now, but whenever designing
a serialization format, you should provide for versionning.
This can be mangled into the type information in the stream, or
treated as a separate (integer) field. When writing the class
out, you always write the latest version. When reading, you
have to read both the type and the version before you can
construct; if you're using the static map suggested in the FAQ,
then the key would be:
struct DeserializeKey
{
std::string type;
int version;
};
Given the situation you are in now, the solution is probably to
mangle the version into the type name in a clearly recognizable
way, say something along the lines of
type_name__version; if the
type_name isn't followed by two underscore,
then use 0. This isn't the most efficient method, but it's
usually acceptable, and will solve the problem with backwards
compatibility, while providing for evolution in the future.
For your precise questions:
In this case, Derived is just a previous version of
Derived1. You can insert the necessary factory function into
the map under the appropriate key.
This is just classical versionning. Version 0 of Base has
a field1 attribute, and when you deserialize, you use it to
initialize field1a, and you initialize field1b empty.
Version 2 of Base has both.
If you mangle the version into the type name, as I suggest
above, you shouldn't have to convert any existing data. Long
term, of course, either some of the older versions simply
disappear from your data sets, so that you can remove the
support for them, or your program keeps getting bigger, with
support for lots of older versions. In practice, I've usually
seen the latter.
maybe Thrift Can help you do it.
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.
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.
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)...