Alex Rivera | Logout

C++: How can a public static member function access private instance member variables?

Asked 2009-10-09T17:05:54.130
9

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

  1. Grabs a Chunk from an inactive chunk pool
  2. Fills the Chunk instance from the input stream using the Chunk's private member variables/functions
  3. 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.

Edit
Report

1 Answer

0

I think singleton pattern fits very well for this. You can access any kind of member functions without worrying if you are accessing it from static functions or not...

answered 2009-10-09T18:12:58.253

Your Answer