Overloading bracket "[]" operator in a templated array class

This is a discussion on Overloading bracket "[]" operator in a templated array class within the C++ Programming forums, part of the General Programming Boards category; I have this book called "Data Structure for Game Programmers" which has been a really great read so far. It ...

  1. #1
    Registered User
    Join Date
    Sep 2006
    Posts
    55

    Overloading bracket "[]" operator in a templated array class

    I have this book called "Data Structure for Game Programmers" which has been a really great read so far. It explains this really useful templated array class which works great but I have a few questions about it.

    Here is just some generic code I threw together to play around with:
    Code:
    #include <cstring>
    
    struct GameState {
    	unsigned int BaseAddress;
    	unsigned int AllocatedSize;
    };
    
    GameState GameStateGlobals;
    
    struct DatumIndex {
    	unsigned short Index;
    	unsigned short Salt;
    };
    
    template <typename T> 
    class DataArray {
    private:
        char           Name[32];
        unsigned short Max;
        unsigned short Size;
        bool           IsValid;
        bool           IdentifierZeroInvalid;
        unsigned short Padding;
        unsigned int   Signature;
        unsigned short NextIndex;
        unsigned short LastIndex;
        DatumIndex     NextDatum;
    	T*             Data;
    public:
        void* operator new(unsigned int size)
    	{
    		return 0;
    	}
    
    	DataArray(const char* name, unsigned int count)
    	{
    		unsigned int DataArraySize = sizeof(DataArray),
    		             DataSize = sizeof(T) * count,
    		             NewArray = GameStateGlobals.BaseAddress + GameStateGlobals.AllocatedSize;
    
    		GameStateGlobals.AllocatedSize += DataArraySize + DataSize;
    
    		memset(this, 0, sizeof(DataArray));
    
    		this->Data = reinterpret_cast<T*>(NewArray + DataArraySize);
    		strcpy_s(this->Name, 31, name);
    		this->Max = count;
    	}
    
        T& operator [](int index)
    	{
    		return this->Data[index];
    	}
    };
    
    struct PlayerDatum
    {
    	int Score;
    	float Speed;
    };
    
    DataArray<PlayerDatum> Players("players", 16);
    
    int main()
    {
    	Players[1].Speed = 1.0f;
    
    	return 0;
    }
    The entire game state memory will be preallocated using VirtualAlloc, so we know that the user will have enough memory before starting the game and so that further memory allocation won't be needed. The game state memory structures I want to be contiguous, meaning each time a new structure is created, it will just add to the allocated size and keep track of the next memory address to use in our big preallocated chunk. This also makes it easier to dump the whole game state to file.

    DataArray will be a "header" right above the array of objects.

    The problem I have with the above code is, I want to be able to have instances of these DataArray objects in the global namespace (accessed from wherever) but created explicitly in code when I want, like inside some other initialization functions.

    I tried overloading the new operator and moving my code into there so I could create a global pointers to objects like so:

    Code:
    DataArray<PlayerDatum>* Players;
    
    int main()
    {
        Players = new DataArray<PlayerDatum>("players", 16);
    }
    But now the problem is, I can't use the "[]" square brackets operator:
    Code:
    Players[3].Score = 1;
    I'd like to have all the functions that work with the DataArray, inside its' class, but I may have to write separate templated functions. Trying to make things easier, ended up being more complex than I thought!

    Any advice on what I am trying to accomplish here?
    Last edited by silentkarma; 01-20-2012 at 07:49 PM.

  2. #2
    Registered User
    Join Date
    Jun 2005
    Posts
    6,677
    Try
    Code:
       (*Players)[3].Score = 1;
    No need to overload operator new or anything like that (except for whatever is implied in your use of VirtualAlloc()). Just remember, if you create any objects (or arrays of objects) with operator new, to delete it with the corresponding operator delete when you no longer need it.
    Right 98% of the time, and don't care about the other 3%.

    If I seem grumpy or unhelpful in reply to you, or tell you you need to demonstrate more effort before you can expect help, it is likely you deserve it. Suck it up, Sunshine, and read this, this, and this before posting again.

  3. #3
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Posts
    23,033
    Honestly, I strongly suggest you avoid using VirtualAlloc. Memory managers are tricky and complex. You will make lots of mistakes, and it will likely be slow.
    Also, don't use char and strcpy. Use std::string! No need for MS extensions, no need for reinterpret_cast, no need for memset.
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. the operator "="error in class "String"
    By boyhailong in forum C++ Programming
    Replies: 9
    Last Post: 07-27-2011, 09:39 PM
  2. "<<" operator overloading
    By maruf10 in forum C++ Programming
    Replies: 10
    Last Post: 07-02-2010, 03:15 AM
  3. Dilemma with "operator overloading"...
    By Petike in forum C++ Programming
    Replies: 3
    Last Post: 08-24-2008, 04:33 PM
  4. OverLoading the "()" parentheses operator
    By wbeasl in forum C++ Programming
    Replies: 9
    Last Post: 09-24-2004, 07:19 AM
  5. Replies: 3
    Last Post: 12-06-2002, 10:02 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21