Why would I use a struct in a program? - c++

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)...

Related

Class in a struct

I have two questions.
I know it is possible to declare class objects in structs. But is it ethical to do that from design point of view?
In my scenario I have a structure with a huge number of member elements and I want to include a class object too. Here I have another question. If I memset() the whole struct the class handle is also reset. So, I check the size of the rest of the struct without the class object and subtract it while I call memset(), to get rid of this problem. (Please note that I am using STL class 'queue' here. And I cannot use sizeof() operator on the object, since it is not overloaded.)
But is this totally an unacceptable way to do that? Can you suggest some solution to this problem?
struct = class (except for default visibility).
If you have a “huge number of members” you are probably doing something wrong, change your design, otherwise it becomes intractable.
It is absolutely fine to nest classes and / or structs, where it makes sense. For instance, it’s common to define nested classes for implementation details (so a linked_list class could have a node member class).
There’s no such thing as a “class object”, and it’s not clear what you mean by that.
Don’t use memset – you probably don’t need it, just use normal constructors and assignment.
And I cannot use sizeof() operator on the object
Wrong, you can use it.
The solution is to avoid memset with classes and structures, and use constructors. In C++11 you can use initialization lists too under various conditions.
There is no much functional difference between classes and structs in c++. Structs exisist in c++ only for backward compatibility with C. So it is ok to have a class objects in structs. However I generally prefer structs that have only member variables with getter and setter. I dont use any functions inside struct that manupulate the data. If i need that then i will use class.

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++ should all member variable use accessors and mutator

I have about 15~20 member variables which needs to be accessed, I was wondering
if it would be good just to let them be public instead of giving every one of them
get/set functions.
The code would be something like
class A { // a singleton class
public:
static A* get();
B x, y, z;
// ... a lot of other object that should only have one copy
// and doesn't change often
private:
A();
virtual ~A();
static A* a;
};
I have also thought about putting the variables into an array, but I don't
know the best way to do a lookup table, would it be better to put them in an array?
EDIT:
Is there a better way than Singleton class to put them in a collection
The C++ world isn't quite as hung up on "everything must be hidden behind accessors/mutators/whatever-they-decide-to-call-them-todays" as some OO-supporting languages.
With that said, it's a bit hard to say what the best approach is, given your limited description.
If your class is simply a 'bag of data' for some other process, than using a struct instead of a class (the only difference is that all members default to public) can be appropriate.
If the class actually does something, however, you might find it more appropriate to group your get/set routines together by function/aspect or interface.
As I mentioned, it's a bit hard to tell without more information.
EDIT: Singleton classes are not smelly code in and of themselves, but you do need to be a bit careful with them. If a singleton is taking care of preference data or something similar, it only makes sense to make individual accessors for each data element.
If, on the other hand, you're storing generic input data in a singleton, it might be time to rethink the design.
You could place them in a POD structure and provide access to an object of that type :
struct VariablesHolder
{
int a;
float b;
char c[20];
};
class A
{
public:
A() : vh()
{
}
VariablesHolder& Access()
{
return vh;
}
const VariablesHolder& Get() const
{
return vh;
}
private:
VariablesHolder vh;
};
No that wouldn't be good. Image you want to change the way they are accessed in the future. For example remove one member variable and let the get/set functions compute its value.
It really depends on why you want to give access to them, how likely they are to change, how much code uses them, how problematic having to rewrite or recompile that code is, how fast access needs to be, whether you need/want virtual access, what's more convenient and intuitive in the using code etc.. Wanting to give access to so many things may be a sign of poor design, or it may be 100% appropriate. Using get/set functions has much more potential benefit for volatile (unstable / possibly subject to frequent tweaks) low-level code that could be used by a large number of client apps.
Given your edit, an array makes sense if your client is likely to want to access the values in a loop, or a numeric index is inherently meaningful. For example, if they're chronologically ordered data samples, an index sounds good. Summarily, arrays make it easier to provide algorithms to work with any or all of the indices - you have to consider whether that's useful to your clients; if not, try to avoid it as it may make it easier to mistakenly access the wrong values, particularly if say two people branch some code, add an extra value at the end, then try to merge their changes. Sometimes it makes sense to provide arrays and named access, or an enum with meaningful names for indices.
This is a horrible design choice, as it allows any component to modify any of these variables. Furthermore, since access to these variables is done directly, you have no way to impose any invariant on the values, and if suddenly you decide to multithread your program, you won't have a single set of functions that need to be mutex-protected, but rather you will have to go off and find every single use of every single data member and individually lock those usages. In general, one should:
Not use singletons or global variables; they introduce subtle, implicit dependencies between components that allow seemingly independent components to interfere with each other.
Make variables const wherever possible and provide setters only where absolutely required.
Never make variables public (unless you are creating a POD struct, and even then, it is best to create POD structs only as an internal implementation detail and not expose them in the API).
Also, you mentioned that you need to use an array. You can use vector<B> or vector<B*> to create a dynamically-sized array of objects of type B or type B*. Rather than using A::getA() to access your singleton instance; it would be better to have functions that need type A to take a parameter of type const A&. This will make the dependency explicit, and it will also limit which functions can modify the members of that class (pass A* or A& to functions that need to mutate it).
As a convention, if you want a data structure to hold several public fields (plain old data), I would suggest using a struct (and use in tandem with other classes -- builder, flyweight, memento, and other design patterns).
Classes generally mean that you're defining an encapsulated data type, so the OOP rule is to hide data members.
In terms of efficiency, modern compilers optimize away calls to accessors/mutators, so the impact on performance would be non-existent.
In terms of extensibility, methods are definitely a win because derived classes would be able to override these (if virtual). Another benefit is that logic to check/observe/notify data can be added if data is accessed via member functions.
Public members in a base class is generally a difficult to keep track of.

C++, How to maintain both data locality and well splitted code structure at every layer of a program?

In my recent project I have a class like this:
class layer1 {
myclassa l1dataa; // layer1 data
...
myclassn l1datan;
public:
void l1datatransformsa()
{
myotherclassa l2dataa; // layer2 data
...
myotherclassn l2datan;
many operations; // way too many operations for a single method
}
void l1datatransformsb() {}
};
The method l1datatransformsa invokes local data and is quite long and robust. I would like to divide its code into smaller meaningful portions (methods) which all work on the same local layer2 data. It can be done in few ways, though none of them seems good enough to me, therefore I'm asking for recommendation on how should it be done:
Breaking the code of "many operations" into private methods of class layer1.
Cons: I would have to pass as arguments to those new methods references to all layer2 data, which is not very elegant as there is too many of them
Rewriting the method l1datatransformsa as a nested class of class layer1 with layer2 data declared as its data members. Then it would be possible to split "many operations" into members of the nested class.
Cons: To access layer1 data from nested class I would have to use reference or pointer to the instance of enclosing class. This will make me include many changes in the code of "many operations" and will make the code less clear. It would be even worse if one would think of a need of splitting in the same manner one of methods of nested class.
The basic idea behind all this is to have a comfortable way of keeping your local data close to the functions or methods which use it and only to them at every layer of your program.
ADDED: "many operations" which we we want to split work both on almost all data members of class layer1 and all local data layer2. They work on layer2 data sequentially and that's why they can be splitted easily, though it's a bit awkward 'programistically'.
First of all, you can increase the clarity of your code by defining your class in a header file, using only prototypes for member functions, and writing the member functions in a separate .cpp file. I'm assuming that you combined these for the sake of making it easier to post here.
The method l1datatransformsa invokes
local data and is quite long and
robust. I would like to divide its
code into smaller meaningful portions
(methods) which all work on the same
local layer2 data.
You might be approaching this incorrectly. If you are only wanting to break down a large member function for the sake of sanity, then all you need are functions, not members. Every function associated with a class is not required to be a member. Only use members here if you will need to call these sub-routines explicitly and individually from somewhere other than inside another member function. When you write your helper functions in the same .cpp file as your class' member functions, declare them static and they will only operate within the scope of that file (effectively limiting them to that class but without giving them the unobstructed data access of a member function). This is an easy way to enforce restrictions on data access as well as promote modularity. Each sub-function will only operate on data passed through the function's parameters (as opposed to a member function which can access all of the class' member data freely).
If you find yourself needing to pass a large number of parameters to a single function, ask yourself if you should A) store them in a struct instead of independent variables and pass the struct to the function or B) break apart the function into several shorter, more focused functions that perform their task on a sub-set of the variables. If these are member variables and you still want to access them individually but pack them into a struct, don't forget you can make the struct private and write simple getter/setter functions for accessing the individual values.
Keep the functions focused; each should do a single task, and do it well. Small functions are easier to read, test, and debug. Don't be afraid to break up your code into several nested layers (l1datatransformsa calls helper func A, which calls helper func B, etc) if it makes the code clearer. If you can write a relatively short name for the function that describes clearly and exactly what the function does (encryptString() or verifyChecksums() instead of dataProcessingStepFour()), you are probably on the right track.
TL:DR version: I don't think nesting a second class is the answer here. If, as you say, the nested class will need to access members of the parent class, that throws up a flag in my head that there is a better way to organize this (classes should function independently and should never assume that they are a child of an object of a particular type). Personally, I would keep l1datatransformsa relatively brief and use helper functions (not member functions) to do the work. If you are needing to pass a lot of different variables to helper functions, either use a struct instead of loose variables or re-think whether that sub-function needs all that information or if it can be split into smaller functions that each operate on less data.
I would conceptualize it, then break up data layers based on conceptual actions and models.
-- New answer --
I removed my old answer because I thought you were looking for a trivial tips. I think you need to do some reading on the tools and techniques you have available to organize and construct software.
Gang Of Four - Design Pattern Book
Modern C++ Design
Generic Programming
The first book is essential, the second builds up some of the concepts that are introduced in the first in C++. The third is quite academic -- but contains a wealth of information, you can probably ignore it.

Structs vs classes in C++ [duplicate]

This question already has answers here:
Closed 14 years ago.
When should someone use structs instead of classes or vice versa in C++? I find myself using structs when a full-blown class managing some information seems like overkill but want to indicate the information being contained are all related. I was wondering what are some good guidelines to be able to tell when one is more appropriate than the other?
Edit:
Found these links while reading the material Stack Overflow indicated was related after the question was submitted:
When should you use a class vs a struct in C++?
What are the differences between struct and class in C++?
Technically, the only difference between the two is that structs are public: by default and classes are private:
Other than that, there is no technical difference.
struct vs class then becomes a purely expressive nuance of the language.
Usually, you avoid putting complicated methods in a struct, and most of the time structs data members will stay public. In a class you want to enforce strong encapsulation.
struct = data is public, with very simple helper methods
class = strongly encapsulated, data is modified / accessed only through methods
I use structs for simple containers of types that provide no constructors or operators.
Classes for everything else.
Use a struct when you simply need a "bucket of stuff" that doesn't have logical invariants that you need to keep. Use a class for anything else.
See also what the C++ FAQ says on the subject.
Use a class if you have methods, a struct if not.
A class should hide all its internals only exposing methods or properties. A struct tends to expose all its internals and has no accessor methods.
Where only one bit of code is accessing some (related) data, a struct may be perfectly reasonable. Where multiple bits of code need to modify the data or if it's anything slightly complicated, a class would be a better bet.
The difference between Classes and Structs are that structs are groups of variables and classes represent objects. Objects have attributes AND methods and be part of a hierarchy.
If you're using C++ to take advantage of the OO capabilities it's best to use classes / objects which are more natural.
I always use class, even for just containers, for consistency. Its purely a choice of style since the difference between the two is negligible.
If you need to control access to the data, you should use classes. If you don't care who is accessing what, and what they're storing in there, then a struct is probably more appropriate.
Also, a class is more appropriate if you need to do any checks on the integrity of the data itself.
See existing questions:
What are the differences between struct and class in C++
When should you use a class vs a struct in C++?
Personally, I use structs when all I need is a container for data (no member functions).
Otherwise, I use classes.
The only time I make an exception to that rule is if I need a simple functor: e.g.
struct compare { bool operator() { ... } };
sort(v.begin(), v.end(), compare());
The need for a public: label would just clutter up the code unnecessarity.
structs in C++ are classes with a default access method of public, so technically other than that default there is no difference and you can use both equivalently.
Yet there are some expectations and natural tendencies, in part because structs in C++ come from C.
My approach: If it has any private data, a constructor/destructor, or any complex member functions (which do more than just conversion upon set/get, etc.), use class.