So, basically, i have a struct, let's say struct someStruct {int A; int B;};
, and a class. For my specific situation, A
must be able to be changed from any scope, but B
should only be changed from inside the class.
I have no idea of what I'm supposed to do here. I have thought about making B
a private property of the class, but it wouldn't make much sense since B
is a property of my struct, and separating it from the struct would make it way too unclear.
If you need more details (i don't see why you would since there's really not much to describe, but i'm putting here anyways), my struct is:
typedef struct {
// A, B, C, position, transform and material should be changed from any scope (don't bother with what they mean, it's not important for the purposes of this question)
vec2 A;
vec2 B;
vec2 C;
vec2 position;
mat2 transform;
Material material;
// this should only be changed from inside the class.
// it identifies the buffer that sends the information of this triangle to the GPU,
// and makes no sense from any scope outside the class
int buffer;
} Triangle;
and my class is (basically):
class Renderer {
// note: many triangles will be stored per buffer, so I can't just assign one buffer to one triangle and vice-versa
GLuint *buffers;
Triangle* triangles;
// some stuff to handle rendering and blah blah blah
}
If you really want it, I can post the full code, but I don't think it could be useful in any way so for now i'm not posting it
preferably try answering the general situation, so I actually learn something from this question, but a more specific answer is very welcome too (e.g. store buffer and triangle data in another way)
CodePudding user response:
Make B
private and declare Renderer
as friend, e.g.:
struct Triangle {
friend class Renderer;
// A, B, C, position, transform and material should be changed from any scope (don't bother with what they mean, it's not important for the purposes of this question)
vec2 A;
private:
vec2 B;
public:
vec2 C;
vec2 position;
mat2 transform;
Material material;
// this should only be changed from inside the class.
// it identifies the buffer that sends the information of this triangle to the GPU,
// and makes no sense from any scope outside the class
int buffer;
};
class Renderer {
public:
// note: many triangles will be stored per buffer, so I can't just assign one buffer to one triangle and vice-versa
GLuint *buffers;
Triangle* triangles;
void setB(vec2 b) { triangles->B = b; } // no error
// some stuff to handle rendering and blah blah blah
};
int main() {
Renderer renderer;
renderer.triangles = new Triangle;
renderer.triangles->A = vec2(1,2); // no error
renderer.setB(vec2(1,2)); // no error
renderer.triangles->B = vec2(1,2); // error: 'vec2 Triangle::B' is private within this context
}