Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

gcc

g++

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... 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++?

like image 659
Bob Murphy Avatar asked Oct 09 '09 17:10

Bob Murphy


2 Answers

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.

like image 112
RichieHindle Avatar answered Sep 19 '22 01:09

RichieHindle


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() {
  ...
}
like image 21
JaredPar Avatar answered Sep 21 '22 01:09

JaredPar