I would like the benefit of a structure so that I can use a pointer to loop through it’s elements. But I would also like to reference the elements without having to reference the structure.
Is there a way to do that?
For example, say I have a class “fruit” that has properties including bananas, apples, pears, etc. I would like to have an instance of fruit, say “myfruit”, and simple refer to the bananas as myfruit.bananas. But if I package the properties as a structure then I would end up with something like myfruit.f.bananas whereas I would rather just write myfruit.bananas. Does that make sense?
To be a little more concrete, here are two examples. The second one has the properties in a struct.
class fruit {
public:
fruit() {}
int getTotal()
{
int total = bananas + oranges + apples + pears + grapes;
total += kiwis + peaches + plums + watermelons;
total += papayas + cherries + tangerines;
return total;
}
uint8_t bananas;
uint8_t oranges;
uint8_t apples;
uint8_t pears;
uint8_t grapes;
uint8_t kiwis;
uint8_t peaches;
uint8_t plums;
uint8_t watermelons;
uint8_t papayas;
uint8_t cherries;
uint8_t tangerines;
};
struct FRUITS {
uint8_t bananas;
uint8_t oranges;
uint8_t apples;
uint8_t pears;
uint8_t grapes;
uint8_t kiwis;
uint8_t peaches;
uint8_t plums;
uint8_t watermelons;
uint8_t papayas;
uint8_t cherries;
uint8_t tangerines;
};
class fruit {
public:
fruit() {}
int getTotal()
{
uint8_t total = 0;
uint8_t *p = (uint8_t *)&f;
for (uint8_t i=0; i<sizeof(FRUITS); i++)
total += *p++;
return total;
}
FRUITS f;
};
First, a c++ class, for all practical purposes, already IS itself a structure, and can be treated in exactly the same way. You can access members of a structure using a pointer to the structure, and you can do the same thing with a pointer or a reference to an instance of a class, using exactly the same syntax. So, creating a structure within a class, simply to make external access to that structure easier, will actually do exactly the opposite.
In this instance I'm interested in internal access to the structure, by some of the class methods. Does that change what you're saying?
To be honest, I am such a bad C++ programmer (or is it c++?) that more often than not I work by example. When I can't find one that's applicable I flounder, trying things somewhat randomly, often giving up and doing it a less elegant way. On my own I doubt I would have figured out what CodingBadly did.
The key difference between a class and a struct is that for the struct, access to members is public by default, whereas for the class, the default is private.