Structs and Classes [duplicate] - c++

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
What are the differences between struct and class in C++
In C++ is there any reason to use a Struct inside of a Class outside of making your own linked list or b-tree?
I've taken a few programming courses in college, but haven't really thought about this until now. It seems like there wouldn't be any benefit from using a struct inside of a class, but I don't have enough experience to know what situations really require certain things. I'm hoping that you experienced programmers can shed some light on this for me.

Yes. When you want to model a complicated object which contains subobjects that are internal to the implementation of the parent object is one excellent case.
There are also many design patterns that can be implemented using such a technique (such as Observer and Delegate).

Structs and classes are the same thing.
In C++ is there any reason to use a Struct inside of a Class outside of making your own linked list or b-tree?
It's a silly question. Of course there is. Inner types are a tool, when you have a problem that requires it, you use it. Iterators, for example, are usually made to be inner types (not that they have to be, but it keeps the type implementation in one place).

Here is a complex scenario: records of sub-records.
struct Title_Record
{
unsigned int id_title;
std::string title_text; // std::string is actually a struct / class.
};
struct Category_Record
{
unsigned int id_category;
std::string category_text;
};
// A record of [id_ingredient, id_title, id_category],
class Ingredient_Entry
{
unsigned int id_ingredient;
Title_Record title; // Use ID field only for storing in database (foreign key).
// But also contain the record for local access.
Category_Record category; // Use ID field only for storing in database (foreign key).
.
};
Every ingredient entry has a title and a category. The title and categories are separate records so that ingredients can share common titles and categories.
Usage:
Title_Record title_table[30]; // Database table of 30 titles.
Category_Record category_table[30]; // Database table of 30 categories.
Remember that the keywords struct and class only differ in their default accessibility.

There are an infinite number of things you can do in C++, so yes, some of them would be best implemented using a struct inside a class.
One reason people use structs is to build an array of them, which makes keeping track of related variables very easy. So one example would be a class that can perform operations on a list of related variables. You are correct that making a linked list is one example where this would be useful.
Another example would be a simple address book or transaction list, where you want to keep separate books that can perform operations on their members.

Related

Modern way to access struct fields by name in C++

I wanted to check if there's an intuitive and easy way to access struct fields by name in modern C++.
I am aware that similar questions have been asked and answered, and C++ reflection is a well investigated subject.
I've came across libraries like:
boost-hana
boost-reflect
visit_struct
magic_get:
But the common point in all these approaches is that, they only allow you to get the total number of fields within the struct or do a certain operation in for_each manner for all the fields of the struct.
Yes, I can obviously check for the specific "name" of the field I'm looking for, by using the for_each functionality provided by these libraries. But I just wanted to check if there is any other trivial/well-know library that already does this.
I would like to be able to deal with arbitrary number of nested structs, which is why I'm looking for something out of the box.
As Louis Go indicated, it would be great to have an accessor like:
auto field = namespace::getField<mystruct>("fieldname");
You can access class members by name using the member access operator. Example:
struct foo {
int bar;
} instance;
instance.bar = 42; // access by name
If you mean to access a member based on a string variable rather than by compile time identifier, then no. C++ still as of C++20 does not have reflection features necessary to achieve this.
Quite often when programmers want this, what they actually need is an associative container such as std::map.

C++ Model View Design

I am currently struggling with the design of an application of the visualization and manipulation of sensor data. I have a database that contains several STL-containers with measured data in it.
std::unordered_map<std::string, std::array<uint16_t, 3366>> data1;
std::unordered_map<std::string, QImage> data2;
std::unordered_map<std::string, std::vector<Point3D>> data3;
I also have different Views (mostly Qt-based) and each view should be associated with a model which is specific to one of the data sets. So data1 is supposed to be processed and manipulated in a class called model1 which is then displayed by means of a class view1 and so forth.
But I cant seem to find a suitable design structure to incorporate this idea. the models grant access to their processed data, but that data is contained in different container structures as given above. That makes it unfeasible to use inheritance with a pure virtual function in the base class like
std::map<...,...> getModelData() = 0;
The initial idea of this inheritance was to avoid code duplication but that doesnt seem to be the right solution here. I know that Qt in their "Model-View" concepts makes use of their QVariant class to have maximum flexibility in terms of types being returned. However, I am wondering, what is the best solution with standard C++ here? I read a lot about striving for loose-coupling, code reuseability, Dependendy Inversion and how to favour composition over inheritance but I do have problems putting these theoretical advise into practice and end up with code bloat and repetitive code most of the times. Can you help me?
Maybe you can give more code but so far, I can give a few hints:
-Can you use QMap instead of std::unordered_map ? It is more agile if you need to tangle with a UI
-Maybe make your second argument of the list a common base type like (code not tested, treat as pseudo code)
class BaseDataClass
{
public:
int getType();
QImage* getImageData();
std::array<uint16_t, 3366>>& getArray();
std::vector<Point3D>>& getVector();
private:
int mType;
BaseDataClass(); //hide ctor or make abstract, as you wish
}
You can avoid code duplicating with this. Make three new classes that each inherit from BaseDataClass. You can then make a method that iterates over all BaseDataClass, checks the type (e.g. 1=QImage; 2 = array ; 3 = vector), and exectues the right method according to the type (get QImage from all type 1`s ...). You also can cast the pointer to the right type then. Which makes it even better if your derived classes gain more and more functionality (like sorting or validating data)

Creating a unique ID for class types C++

My goal here is to create a unique ID (starting a 0) for each child of a specific class. I'm not sure if it is possible in the way i want, but i figured i'd ask here as a last resort.
Some context:
I'm creating my own 2D game engine and i want it to have an ECS as it's back bone (Before anyone says anything, i'm doing this as a learning experience, i know i could just use an already existing game engine). My idea is that each class that implements the 'EntityComponent' class should have a unique ID applied to it. This needs to be per child, not per object. I want to use this ID as the index for an array to find the component of an entity. The actual ID that each Component gets is unimportant and each component does not need to be assigned the ID every run time.
My hope is there is some way to create something similar to a static variable per class (That implements the Entity Component class). It needs to be quick to get this value so doing an unordered_map lookup is slower than i would like. One thing i do not want to do is setting the ID for every component myself. This could cause problems once many components are made and could cause problems if i forget to set it or set two components to the same ID.
One idea i had was to make a variable in EntityComponent called ID (And a getter to get it). When the entity is constructed it looks up an unordered map (which was made at run time, assigning an ID to each class) for what ID it should have. The price of looking up once at construction is fine. The only problem i see with this is there is a lot of redundant data (Though overall it seems it would account to a pretty small amount). With this, every single transform component would have to store that it its ID is x. This means potentially thousands upon thousands of transform components are storing this ID value, when only 1 really needs to.
Basically i am after an extremely quick way to find an ID for a class TYPE. This can be through a lookup, but it needs to be a quick lookup. I would like something faster than unordered_map if possible. If this can be done through compile time tricks (Maybe enums?) or maybe even templates i would love to hear your ideas. I know premature optimisation is the bad, but being able to get a component fast is a pretty big thing.
What i'm asking might very well be impossible. Just thought i'd ask here to make sure first. I should also note i'm trying to avoid implementation of this in the children classes. I'd like to not have to set up the same code for each child class to create an id.
Thank you.
In order to get something corresponding to the actual type of an object, it either needs to be in the object itself or accessed via a virtual function. Otherwise the type will be determined by the type of the variable it is associated with.
A common option when speed and size are both important is to have an integer identifier associated with each type (when the full type list is known at compile time) and use that integer value in a specific way when you want to do something based on the type.
The integer mechanism usually uses an enum for generating the corresponding value for each type and has that field in every object.
The virtual method variety, I've used boost::uuid and a static data member in each class and a virtual method get'er for it.
Declare a virtual function newId() in EntityComponent.
Implement this function to get and increment a static variable in each class, which children you want to have a unique Id.
Assign Id in the constructor:
mId = newId();
don't know this if this is what you meant and i know this is an old post however this is how im currently dealing with a similar issue, maybe it will help someone else.
(Im also doing this as a learning experience for uni :) )
in the controlling class or its own utility class:
enum class EntityType{ TYPE_ONE = 0, TYPE_TWO =1};
in class header:
#include "EntityType.h"
class Whatever{
public:
inline void getType(){return _type;}
OR
inline void getType(){return EntityType::TYPE_ONE;}
private:
EntityType _type = EntityType::TYPE_ONE;
};
Hope this is helpful to anyone :)

Categorizing items the right way

I'm working on an application which among other things downloads items that belong to a certain category form a server. I want to make the downloader look like this:
class Downloader
{
Downloader(const ItemCategoryBase &category);
...
}
Each class derived from ItemCategoryBase will provide it's category ID trough a virtual function (in fact that's the only thing each derived class will do).
The issue I'm having is that I have a total of 120 item categories and writing a derived class for each one is going to be painful.
I've considered using a primitive to hold the ID but, I do not wish to implement range checking and throw exceptions in case the ID is out of range mainly because category IDs aren't all part of the same interval.
What I'm looking for is an efficient way of writing code that would fit the scheme above.
Any help is highly appreciated.
If you really have determined that this is the right way to do things, then I would suggest writing a code generator to handle it for you: create a CSV document containing all the Category ID's, and write an app that inserts each ID into template header/source files, and saves it out.. (For instance, put "$CATEGORY_ID" in wherever the Category ID goes in the files, and then just do a replace on "$CATEGORY_ID" with each ID in turn.)
However, I'm not sure I understand your statement: "I've considered using a primitive to hold the ID but, I do not wish to implement range checking and throw exceptions in case the ID is out of range mainly because category IDs aren't all part of the same interval." I can't imagine a case in which you wouldn't have to handle the complexity somewhere in your application anyway, and the range checking wouldn't be hard: just put all the valid Category IDs into a list structure of whatever your ID type is, and a simple index lookup call can answer whether the ID is part of that list.
If I have misunderstood you, what exactly is it about your setup that makes dealing with 120 ItemCategoryBase derived classes simpler than one ItemCategoryBase base class validated against a list of the IDs? You say "mainly because category IDs aren't all part of the same interval," so perhaps the checking against a list would give you what you need there. Otherwise, can you explain a bit more about how it works? Although I realize there are always exceptions, 120 classes doing nothing other than providing different IDs really strikes me as something that's unlikely to be a solution that will serve you well in the long run.
Since you're using C++, why not use templates and specify a non-type template parameter containing the ID?
For example, supposing that the category is an integer:
template<int category_id>
class Downloader : public ItemCategoryBase
{
public:
virtual int get_id()
{
return category_id;
}
};
You might as well let the compiler do the work for you.

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.