Extending struct member with another struct - c++

Instead of making a new question I will edit this one by completely erasing the previous one, hopefully making it less confusing.
Wall of text.
I have a basic struct that has some basic values, such as image width, height and x and y positions, like so:
struct obj {
int id = 0;
float x = 0;
float y = 0;
int image_w = 0;
int image_h = 0;
int depth = 0;
}
I then have an initialiser function that creates the members of that struct and stores them in an array. If that array is named "instance" then individual members and their values can be accessed by simply doing this: instance[number].x etc..
Then I have a loop or two which handle all these members and do so in the order of their depth value, defined in struct and set in initialiser function. Like so (simplified):
for (i=0;i<maxdepth;i++) {
if (instance[n].depth == i) { doStuff; }
}
In "doStuff" function I check the members' id value in a switch statement and then have them do whatever I want inside case labels; this gives me the option to have some individual behavior within the same struct. And here is where the problem is. Although this works just fine I can't have individual fixed (or starting) variables within certain members without every member having those same variables and obviously with enough members this eventually results in a struct that is simply undesirably big and has a lot of redundancy; wasted resources. E.g I want some members to have speed and direction variables but don't want to give them to static members of the same struct that don't need them.
The question is, how do I achieve this effect without changing the fundamental idea of using structs or is there a better alternative to do this?
And I'm sorry about formatting and all; this is my first question on this website.

My understanding of structs is that the bigger it is the more time it takes to access its individual variables.
Your understanding is fundamentally mistaken. The size of a struct has little (if any) effect on the time required to access an individual variable inside that struct.
Regardless of that, however, your basic idea of structuring the data so one struct contains (or owns a pointer to) some other structs is perfectly fine and reasonable.
What's not so fine or reasonable is making that pointer essentially un-typed so it can refer to any other type. If you want a collection of clothes, you'd probably start with a clothing base class, and then derive various other types from that (coat, shirt, slacks, jeans, etc.). Then the person type might contain (for example) a vector of pointers to clothing, so it can contain pointers to all the other types derived from clothing.
As far as "extending scope" goes...well, I can't say much beyond the fact that I can't make much sense of what you're trying to say there.

Related

Can I create Union of classes

I have two classes for communication that will never exist at the same time but both will be in use.
Example:
class CommA
{
public:
void SendA();
...
private:
ProtocolA a;
...
}
class CommB
{
public:
void SendB();
...
private:
ProtocolB b;
...
}
Is it possible to hold them in Union to save memory?
union CommAB
{
CommA a;
CommB b;
}
The std::variant was already raised by others in comments and answers. I'll explain why it is the recommended approach.
There is an important thing to know about unions: only one member of a union can be active at any time. If you create an AB object, it's either a or b, and if you access the wrong one, it's UB. How do you know which one is the active one? Fortunately the standard provides some guarantees: if classes of all union-members start with the same common members, you can access those safely. The usual trick is then to have a first member in all the classes of the union to determine which is the active one. Another issue can be when you have an active member and want to change it.
The advantage of the variant is that it takes care of these practical aspects without you having to worry, and without having to adjust the classes of the members.
Since you are looking for space: the union takes the space of its largest member. So if you have to add a common extra member in your classes to track the active union member, your union will be larger that either the initial A or B. The variant does the work for you, so it will be larger as well.

Member function static variable vs member variable [duplicate]

This question already has answers here:
Static vs. member variable
(4 answers)
Closed 8 years ago.
Is it a good practice to use a static variable inside member function instead of member variable for a variable that should preserve its value between function calls?
Consider the following example: I have a class with an update() function where some 3D object is being rotated every frame. I sometimes see the following code:
void Class::update(float frameTime)
{
static float rotation = 0.0f;
rotation + = m_rotationSpeed * frameTime
if (rotation >= 360.0f) rotation -= 360.0f;
// ...
}
This can just as well be implemented using a member variable.
Are there any reasons to prefer one implementation over the other? It seems to me like using a static like this does improve encapsulation and also results in a smaller object, but on the other hand it seems somewhat less intuitive.
Please note that a class like that is usually meant to be used in single instance, and, since C++11, static variable should be thread safe.
It makes very little sense to use a static variable here, because all instances of Class will access the same variable. It is very unlikely that you need to share rotation between instances like this.
If you want to restrict a class to being a single instance, then you have to make sure it can only be instantiated once. But this is usually a sign that a re-design is in order.
I would say if you use singleton approach it's meaningless using static field. Even if your project won't get any bigger.
Do not go with static typically. Static means you can use it without declaring an object. Static doesn't fit your case. Just because there's only one of it doesn't mean it needs to be static.
Static is useful usually when you have something perhaps you want to be able to compare to without two instances of the object.
I.e perhaps you have a shape object, and it has an enum for color. By making the enum static, you can do something such as if(myShape.shapeColor == Shape::color::red) Usually however, I stay away from static. It's one of those things that has its uses and doesn't need to be broadened any further.
Edit:
Actually, making the enum static in that case won't change anything. I guess I'll to try to keep my answer somewhat valid, and so I'll pretend that you could not use enums in this case. (Even though this is a c++ question, I'm just getting a point across). You could declare say, a series of constant static integers. You would not be forced to have two objects for comparisons.
Using static like this is ok for a small application however as the application grows larger there then becomes the issue of using static where you would want to use a member variable due to the scalability of it over using static.
There is no 'good pratice' here as they don't do the same thing :
A member variable (attribute) will be updated only by the current instance of the class.
A static variable will be modified by all the instances of that class.
For example the class
class Foo
{
void bar()
{
static int bar = 0;
std::cout << bar << std::endl;
bar++;
}
};
given this main
int main()
{
Foo one, two;
one.bar();
two.bar();
two.bar();
one.bar();
}
will output
1
2
3
4

Difference between struct and enum?

I am newbie to C++, and want to understand what is the difference between saying
typedef enum stateUpdateReasonCode
{
a=1,
b=2,
c=3
} StateUpdateReasonCode;
and
struct StateUpdateReasonCode
{
a=1,
b=2,
c=3
};
What is difference between them ? Wy would we use one over another ?
Kind Regards
An enum and a struct are totally different concepts, fulfilling different purposes.
An enum lets you declare a series of identifiers for use in your code. The compiler replaces them with numbers for you. It's often useful for making your code more readable and maintainable, because you can use descriptive names without the performance penalty of string comparisons. It can also make the code less bug-prone because you don't have to keep writing in specific numbers everywhere, which could go wrong if a number changes.
A struct is a data structure. At its simplest, it contains zero or more pieces of data (variables or objects), grouped together so they can be stored, processed, or passed as a single unit. You can usually have multiple copies (or instances) of it. A struct can be a lot more complex though. It's actually exactly the same as a class, except that members are public by default instead of private. Like a class, a struct can have member functions and template parameters and so on.
One of the vital difference between structs and enums is that an enum doesn't exist at run-time. It's only for your benefit when you're read/writing the code. However, instances of structs (and classes) certainly can exist in memory at runtime.
From a coding standpoint, each identifier in an enum doesn't have its own type. Every member within a struct must have a type.
The first compiles, the second does not.
Your struct declaration is invalid. In plain C struct are so called record types, they contain a set of values (each with it's own type). In C++ this capability is expanded and a struct is basically equivalent to a class. The struct can now have base classes, member functions, access specifiers, conversion operators, operator overloads and so on.
An enum is an enumeration type: it describes a finite set of states. In C and C++ the fact that enum values are convertible to integers is more or less a leaking abstraction.
They are fundamentally different.
Struct
For a struct these values are defaults (only for C++ 11 onwards) for the data structure. A "struct" is a structure of data, for example:
struct Car
{
float enginesize = 0.0f;
char modelname[100];
};
You would assign these values after you've declared a variable of the type Car etc:
{
Car brum = {1.0f}; // Specify a a size: don't use default
Car zoom; // Will default to 0.0 as specified in the struct
}
Without a default value it will undefined (something random).
Enum
An enumeration, however, is renamed numeric values: it's a very handy way of naming numeric constants. e.g.
enum EngineType
{
Petrol,
Diesel,
Electric,
LPG = 34 // NB assigning values is optional
};
enum work like the constants where you want to specify the the value with a word. Like for the days of week one want that sun = 0, mon = 1 and so on. In this case enum can be used.
struct is totally different from the enum. It can be seen analogues to the class in c++ or any other programming language. structure is a user defined data type which can be used to store the info. Like in address different fields can be there street , zip code etc.
the first one compiles as it stores the value of an enum and second one does not as struct variable data members values can be assigned by creating a struct variable.

Map functions of a class

Before I was trying to map my classes and namespaces, by using static calls I succeded and now I need to map the functions of my classes because they will be used dynamically.
Firstly I was thinking to hardcode in the constructor so I can assign a std:map with the string of the name of function pointing to the function itself.
for example:
class A{
int B(){
return 1;
}
};
int main(){
A *a = new A();
vector<string, int (*)()> vec;
vector["A.B"] = a.B;
}
By that I have mapped the function B on A class, I know that I only mapped the function the instance and thats B is not static to be globally mapped.
But thats what I need, at somepoint someone will give me a string and I must call the right function of an instance of a class.
My question is if I only can do that by hardcoding at the constructor, since this is a instance scope we are talking or if there is somehow a way to do this in the declaration of the function, like here for namespaces and classes:
Somehow register my classes in a list
If I understand you correctly, you want your map to store a pointer that can be used to call a member function on an instance, the value being chosen from the map at run time. I'm going to assume that this is the right thing to do, and that there isn't a simpler way to solve the same problem. Quite often when you end up in strange C++ backwaters it's a sign that you need to look again at the problem you think you have, and see whether this is the only way to solve it.
The problem with using an ordinary function pointer is that a non-static member function is not an ordinary function. Suppose you could point to a member function with an ordinary function pointer, what would happen when you dereferenced that pointer and called the function? The member function needs an object to operate on, and the syntax doesn't provide a way to pass this object in.
You need a pointer to member, which is a slightly obscure feature with relatively tricky syntax. While an ordinary pointer abstracts an object, a pointer to member abstracts a member on a class; the pointer specifies which class member should be called, but not which object to obtain the member from (that will be specified when the pointer is used). We can use it something like this:
class B;
class A
{
B some_function()
{ /* ... */ }
};
B (A::* myval)() = A::some_function;
Here myval is a variable that indicates one of the members of class A, in this case the member some_function (though it could point to any other member of A of the same type). We can pass myval round wherever we want (e.g. storing it in an STL container, as in your example) and then when we want to call the function, we specify the instance it should be called on in order to locate the function:
A some_a;
B newly_created_b = (some_a.*myval)();
This works for a particular case, but it won't solve your general issue, because member pointers contain the class they refer to as part of the definition. That is, the following two variables are of entirely different types:
B (Foo::* first_variable)() = Foo::some_function;
B (Bar::* second_variable)() = Bar::some_function;
Even though both functions can produce a B when called without arguments, the two values operate on different classes and therefore you can't assign a value of one type to a variable of the other type. This of course rules out storing these different types in a single STL container.
If you're committed to storing these in a container, you'll have to go with a functor-based solution like Charles Salvia proposes.
If I understand you correctly, you're going to have a class like:
struct Foo
{
int bar();
};
And the user will input a string like "Foo::bar", and from that string you need to call the member function Foo::bar?
If so, it's rather awkward to code a flexible solution in C++, due to the static type system. You can use an std::map where the key is a string, and the value is a member function pointer, (or std::mem_fun_t object), but this will only work on a single class, and only on member functions with the same signature.
You could do something like:
#include <iostream>
#include <map>
#include <functional>
struct Foo
{
int bar() { std::cout << "Called Foo::bar!" << std::endl; }
};
int main()
{
std::map<std::string, std::mem_fun_t<int, Foo> > m;
m.insert(std::make_pair("Foo::bar", std::mem_fun(&Foo::bar)));
Foo f;
std::map<std::string, std::mem_fun_t<int, Foo> >::iterator it = m.find("Foo::bar");
std::mem_fun_t<int, Foo> mf = it->second;
mf(&f); // calls Foo::bar
}
just found(using google) a topic to the same question I had with an answer.
What is the simplest way to create and call dynamically a class method in C++?
I didn't try it yet but makes sense, I will ask again later if it doesn't work
ty!
Joe
I must call the right function of an instance of a class.
You need to call a specific method on an existing instance, or you need to create an instance of the appropriate type and call the method?
If it's the former, then you need a std::map or similar that lets you look up instances from their names.
If it's the latter, that's basically what serialization frameworks need to do in order to create the correct type of object when de-serializing, the object that knows how to read the next bit of data. You might take a look at how the Boost serialization library handles it:
boost.org/doc/libs/1_40_0/libs/serialization/doc/serialization.html
Are you doing this in some kind of tight loop where you need the efficiency of a good map? If so, then member function pointers (as you linked to above) is a good way to go. (At least it is after you work around the problem #Tim mentioned of keeping member function pointers to different types in the same collection ... let the language abuse begin!)
On the other hand, if this is in code that's user-driven, it might be more legible to just be totally uncool and write:
if( funcName=="A.b" )
{
A a;
a.b();
} else
// etc etc etc
For the higher-performace case, you can supplement the same approach with a parse step and some integer constants (or an enum) and use a switch. Depending on your compiler, you might actually end up with better performance than using member function pointers in a map:
switch( parse(funcName) )
{
case A_b:
{
A a;
a.b();
}
break;
}
(Of course this breaks down if you want to populate your list of possibilities from different places ... for example if each class is going to register itself during startup. But if you have that kind of object infrastructure then you should be using interfaces instead of pointers in the first place!)

a struct doesn't belong in an object oriented program

Or does it?
Should an object-oriented design use a language construct that exposes member data by default, if there is an equally useful construct that properly hides data members?
EDIT: One of the responders mentioned that if there's no invariant one can use a struct. That's an interesting observation: a struct is a data structure, i.e. it contains related data. If the data members in a struct are related isn't there's always an invariant?
In C++, structs and classes are identical except for the default public/privateness of their members. (This default is easily, and usually, overridden.)
However, most programmers think of a struct as a "data object" and a class as an "interactive object". That's not a bad thing; and in fact should be taken advantage of. If something is just an inanimate lump of data (even maybe if it has a couple of inspector methods), use a struct for it; it'll save a bit of effort when a programmer is trying to see what it's for.
Don't be a hiding zealot. If your get/set methods do nothing but simply copy verbatim the value onto/from a hidden, private field, you've gained nothing over a public member and only complicate unnecessarily your class (and, depending on the intelligence of the compiler, slow its usage a bit).
There's a case for not allowing direct access when your setter methods do some validation, copy the data somewhere else, process it a bit before storing it, etc. Same in the case of getters that actually calculate the value they return from multiple internal sources, and hide the way it's derived (I believe Bertrand Meyer speaks a bit about this in his book)
Or if allowing the users of your class to directly change such a value would have unintended side effects or breaks an assumption some of your member classes have about the values. On those situations, by all means, do hide your values.
For instance, for a simple "Point" class, that only holds a couple coordinates and colour, and methods to "Plot" it and "Hide" it on screen, I would see no point in not allowing the user to directly set the values for its fields.
In C# for example I use structs for some simple better-left-as-values data types:
public struct Point
{
int X;
int Y;
}
and for any P/Invoke to libraries where the arguments are structs you'll have to use them for certain.
Do they belong in the general design of an application? Of course they do, use a struct when it makes sense to do so. Just like you'd use a enum with bit flags when it makes sense to do so instead of resorting to some complicated string parsing for storing combined values.
In C++, the difference between a struct and a class is the default visibility of its contents (i.e. public for a struct, and private for a class). I guess this difference was to keep C compatibility.
But semantically, I guess this is subject to interpretation.
An example of struct
In a struct, everything is public (by default), meaning the user can modify each data value as desired, and still the struct remains a valid object. Example of struct:
struct CPoint
{
int x ;
int y ;
CPoint() : x(0), y(0) {}
int getDistanceFromOrigin() const
{
return std::sqrt(x * x + y * y) ;
}
} ;
inline CPoint operator + (const CPoint & lhs, const CPoint & rhs)
{
CPoint r(lhs) ;
r.x += rhs.x ;
r.y += rhs.y ;
return r ;
}
You can change the x value of a CPoint, and it still remains a valid CPoint.
Note that, unlike some believe, a C++ struct can (and should) have constructors, methods and non-member functions attached to its interface, as shown above.
An example of class
In a class, everything is private (by default), meaning the user can modify the data only through a well defined interface, because the class must keep its internals valid. Example of class:
class CString
{
public :
CString(const char * p) { /* etc. */ } ;
CString(const CString & p) { /* etc. */ } ;
const char * getString() const { return this->m_pString ; }
size_t getSize() const { return this->m_iSize ; }
void copy { /* code for string copy */ }
void concat { /* code for string concatenation */ }
private :
size_t m_iSize ;
char * m_pString ;
} ;
inline CString operator + (const CString & lhs, const CString & rhs)
{
CString r(lhs) ;
r.concat(rhs) ;
return r ;
}
You see that when you call concat, both the pointer could need reallocation (to increase its size), and the size of the string must be updated automatically. You can't let the user modify the string by hand, and forget updating the size.
So, the class must protect its internal, and be sure everything will be correctly updated when needed.
Conclusion
For me, the difference between a struct and a class is the dependencies between the aggregated data.
If each and every piece of data is independent from all the others, then perhaps you should consider a struct (i.e., a class with public data member).
If not, or if in doubt, use a class.
Now, of course, in C#, the struct and class are two different type of objects (i.e. value types for structs, and referenced types for classes). But this is out of this topic, I guess.
Technically, a struct is a class with the default visibility of public (a real class has a default visibility of private).
There is more of a distinction in common use.
A struct is normally just a collection of data, to be examined and processed by other code.
A class is normally more of a thing, maintaining some sort of control over its data, and with behavior specified by associated functions.
Typically, classes are more useful, but every so often there's uses for something like a C struct, and it's useful to have a notational difference to show it.
The matter is easy. If the class does have invariants to guarantee, you should never make the members constraining the invariant public.
If your struct is merely an aggregate of different objects, and doesn't have an invariant to hold, you are indeed free and encouraged to put its members public. That's the way std::pair<T, U> in C++ does it.
What's that invariant stuff?
Simple example: Consider you have a Point class whose x and y members must always be >= 0 . You can make an invariant stating
/* x >= 0 && y >= 0 for this classes' objects. */
If you now make those members public, clients could simply change x and y, and your invariant could break easily. If the members, however, are allowed to contain all possible values fitting their own invariants respectively, you could of course just make those members public: You wouldn't add any protection to them anyway.
A struct is essentially a model class but with different syntax.
public struct Point {
int x;
int y;
}
is logically the same as:
public class Point {
private int x;
private int y;
public void setX(int x) { this.x=x; }
public int getX(); { return x; }
public void setY(int y) { this.y=y; }
public int getY(); { return y; }
}
Both are a mutable model that holds pair of integer values called x and y. So I would say that it's a valid object oriented construct.
Yes. It's like a mini-class.
Yes, they do. They have different semantic than classes. A struct is generally considered and treated as a value type, while a class is generally considered and treated as a reference type. The difference is not as much pronunciated in every day programming; however, it is an imprtant difference when it comes to things like marshalling, COM interop and passing instances around.
I use structs regularly - mostly for data received from the network or hardware. They are usually wrapped in a class for use by higher level parts of the program.
My rule of thumb is a struct is always pure data, except for a constructor. Anything else is a class.
Most answers seem to be in favor of a struct as something to be acceptable and useful, as long as it does not have a behavior (i.e. methods). That seems fair enough.
However, you can never be sure that your object does not evolve into something that may need behavior, and hence some control over its data members. If you're lucky enough that you have control over all users of your struct, you can go over all uses of all data members. But what if you don't have access to all users?
A struct, as used in C or C++, and the struct used in C# ( or any .Net language ), are such different animals that they probably should not even have the same name... Just about any generalization about structs in one language can easily be false, or true for a completely unrelated reason, in the other.
If there is a need for invariant, make it a class. Otherwise, struct is OK.
See these similar questions:
When should you use a class vs a struct in C++?
What are the differences between struct and class in C++
plus:
According to Stroustrup in the C++ Programming Language:
Which style you use depends on circumstances and taste. I usually prefer to use struct for classes that have all data public. I think of such classes as "not quite proper types, just data structures."
Formally, in C++ a struct is a class with the visibility of its members set to public by default. By tradition structs are used to group collection of homogeneous data that have no particular reasons for being accessed by specific methods.
The public visibility of its members makes structs preferred to class to implement policy classes and metafunctions.
There's nothing wrong with using structs per se, but if you're finding yourself needing them, you should ask what's wrong with your analysis. Consider, eg, the Point class above: it gives some little improvement in readability, since you can always use
Point foo;
//...
foo.x = bar;
in place of, say, having a two element array as in
#define X 0
#define Y 1
//...
foo[X] = bar;
But classes are meant to hide details behind a contract. If your Point is in some normalized space, the values may range in the half-open interval [0.0..1.0); if it's a screen they may range in [0..1023]. If you use a struct in place of accessors, how will you keep someone from assigning foo.x = 1023 when x should be everywhere < 1.0?
The only reason C++ programmers used structs for Points is that back at the dawn of time --- 20 years ago, when C++ was new --- inlining wasn't handled very well, so that foo.setX(1023) actually took more instructions than foo.x = 1023. That's no longer true.
Structs are fine as long as they're kept small. As you probably know, they are allocated on the stack (not the heap) so you need to watch the size. They can come in handy for small data structures like Point, Size, etc. A class is usually the better choice though, being a reference type and all.