InvisiblePanda
InvisiblePanda

Reputation: 1609

Variables with static/const, which to use in this case?

I am trying to create a small "world" made out of blocks, similar to Voxel engines, but a little different.

For this, I thought about creating a class, say Block, that has a method draw(). Let's think of a Block as a cuboid. Then I can characterize every Block by its length, width, height, and draw it by scaling it via the model matrix for a fixed array of vertices (namely that of a unit cube centered around the origin).

My question is: what would be the best way to declare this array consisting of 8 vertices of type GLfloat (that is, 24 GLfloat entries). Since I may be having many blocks, I want the array to be saved somewhere only once, and every instance of Block shall use this exact array, instead of carrying it around with every Block. What's the best way to accomplish this? Since I am quite new to this, I couldn't really understand if static or const (or both?) can be helpful here. I thought about doing

const GLfloat unit_cube_vertices = { ... };

class Block
{ ... };

Is there a better/canonical way?

Upvotes: 1

Views: 171

Answers (2)

mark
mark

Reputation: 5459

If the array is to be used only by your class (or in relationship with the class), I'd declare it as part of the class (note that static here will mean there's only one copy), i.e.

class Block {
public:  // or private if not used anywhere else
    static const GLfloat unit_cube_vertices[24];
};

If it's to be used globally, keep it as you declared it.

Upvotes: 2

Kilian Brendel
Kilian Brendel

Reputation: 558

This question doesn't seem to have much to do with static/const. Those two keywords just tell C++ how the storage may be accessed, and where it should be visible. What you are doing is totally fine.

const means the variable mustn't be changed anymore. In rare cases, the compiler can optimize your code if it knows the values aren't going to change.

static refers to the visibility of the object in different compilation units (~different files in your project). Variables with static linkage will not be seen in other compilation units.

Upvotes: 1

Related Questions