Advertisement Jump to content
Sign in to follow this  

C++/Classes/Static Variable

This topic is 3826 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Hi Everyone! Topic: I have a quick question regarding static variables in classes. Background: I'm creating a simple 2D brick breaker game. The Bricks are all the same texture and therefore have the same pixel information. In my Brick Class I have an array of Boolean values that hold if a pixel at x,y on the image is transparent. Question: Instead of having to extract all the information (transparent pixel or not) for every brick I would like to only have to do it once. I was wondering if it was possible to make the array static so if it changes in one instance of a brick it changes in all. Thus, I would only have to get the data once. Other Possible Solutions: 1. My current solution is for every brick I get the pixel information from the texture. 2. Have the array outside of the class - I'd like it to be contained within the class if that's possible. Code: The way my code is organized is there is a GameObject class that has a p_PixelDataArray[x][y] . I would like to override this in the Brick class to be something like static p_PixelDataArray. GameObject bool** p_PixelDataArray Brick : GameObject static bool** p_PixelDataArray Conclusion: I'm not sure if this is correct use of static, or if I'm thinking about it wrong. I'm open for suggestions please! Thank you, -MsWho.

Share this post

Link to post
Share on other sites
Here's a working example using a private static class member.

#include <iostream>
using namespace std;

#define WIDTH 4
#define HEIGHT 4

class GameObject
void ModPixelDataArray (int x, int y, bool state)
p_PixelDataArray[x][y] = state;

void OutputPixelDataArray (void)
for (int y = 0; y < HEIGHT; y++)
for (int x = 0; x < WIDTH; x++)
cout << p_PixelDataArray[x][y];
cout << endl;


// Can only be modified from within GameObject
static bool p_PixelDataArray[WIDTH][HEIGHT];

// Static members have to be contained outside the class
bool GameObject::p_PixelDataArray[WIDTH][HEIGHT];

int main (void)

// Create object
GameObject go;

// Modify the bool matrix
go.ModPixelDataArray(2, 2, true);

// Display matrix

// Create object and display
GameObject go2;

// Pause

Share this post

Link to post
Share on other sites
Sign in to follow this  

  • Advertisement

Important Information

By using, you agree to our community Guidelines, Terms of Use, and Privacy Policy. is your game development community. Create an account for your GameDev Portfolio and participate in the largest developer community in the games industry.

Sign me up!