My thoughts where that if I have a class and I want seperated containers in that class that hold private variables I could use a struct to contain the variables.
Declaring a struct in a class, like declaring a struct anywhere else, just declares a type. It's not an object in itself and must be instantiated before it exists as an object.
If the struct is useful as an organizing type inside the class then there is a good chance it will be useful outside the class. In particular, it may be useful to return or accept a copy or reference to the struct.
1 2 3 4 5 6 7 8 9
struct Point {
int x, y;
};
class Animal {
Point position;
public:
Point getpos() const { return position; }
};
Private structs are an implementation detail and there should generally be an actual need for a struct.
1 2 3 4 5 6 7 8 9 10
class List {
struct Node {
Node *next;
int data;
};
Node* root = nullptr;
size_t size = 0;
public:
//...
};
You need to give more detail to determine what's right for your situation.
class charSheet {
struct stats {
int stat01;
int stat02;
}stats;
}
struct skills {
int skill01;
int skill02;
}
// to call or set
charSheet player01;
player01.stat.stat01 = 4;
An array would mean I would need to know what skill [1] was. With a struct I can call them directly by name more intuitively. The one thing I don't know why is: see below
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
class charSheet {
struct stats {//<--- What is "stats" function here? I am just declaring the type?
int stat01;
int stat02;
}stats;//<----Why do I need to do this?? Initializing the struct for access?
struct skills {
int skill01;
int skill02;
}skills;//<----Why do I need to do this??
// to call or set
int main()
{
charSheet player01;
player01.stats.stat01 = 4;
cout << player01.stats.stat01 << endl;
}
Why do you need to create an instance of the struct contained in your class? For the same reason why you need to instantiate an object of your class in main.