I'm writing a C++ class to read input from a file into preallocated buffers called "chunks".
I want the caller to be able to call a public static Chunk class method called GetNextFilledChunk(), which
- Grabs a Chunk from an inactive chunk pool
- Fills the Chunk instance from the input stream using the Chunk's private member variables/functions
- Returns a pointer to the Chunk to the caller
But step 2 is giving me fits. No matter what I've tried, trying to get to the Chunk instance's private member variables/functions causes g++ 4.2.1 to emit errors.
Here's a piece of the class definition from the header file:
class Chunk
{
public:
Chunk();
...
static Chunk* GetNextFilledChunk();
...
private:
...
ssize_t m_ActualTextSize;
};
And here's part of the source file that shows the problem:
#include "Chunk.h"
Chunk::
Chunk* GetNextFilledChunk()
{
...
theChunk = sInactiveChunks.top();
sInactiveChunks.pop();
...
theChunk->m_ActualTextSize = TextSize(); // PROBLEM IS HERE
...
return theChunk;
}
As shown, g++ complains that GetNextFilledChunk() is trying to access a private member of Chunk.
Then I thought, maybe it needs to be a "friend". But everything I've tried to do in header file to make GetNextFilledChunk() a friend results in an error. For instance:
friend static Chunk* GetNextFilledChunk();
results in "Chunk.h:23: warning: ‘Chunk* GetNextFilledChunk()’ declared ‘static’ but never defined"
What I find truly bizarre is that if I simply make GetNextFilledChunk() a plain old function, not a static member function, I can "friend" it and everybody is happy. But that seems silly - why should one be able to do something in a class from a non-class function that can't be done from a static member function?
So... How can Chunk's s GetNextFilledChunk() function access private member variables of a Chunk instance?
And if it can't be done, is it an inherent part of C++, or simply a bug in g++?