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
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++?
This looks a little bizarre:
Chunk::
Chunk* GetNextFilledChunk()
{
Is that a typo? Should it be:
Chunk* Chunk::GetNextFilledChunk()
{
? It looks like you're accidentally defining GetNextFilledChunk
to be a plain function rather than a member of Chunk
.
The problem is in your definition of GetNextFilledChunk. As written in the CPP file you have declared a non-member function which is preceeded by a badly formed label. It will not line up with the member function in the header.
The correct signature is as follows
Chunk*
Chunk::GetNextFilledChunk() {
...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With