tags:

views:

105

answers:

3

How can i access class obect types in a statically declared private member function?:

class Y
{
..
private:
    friend class X;
    X *myX;
}; 
class X
{
public:
      friend class Y;
private:
    static int foo( const char * const key );
    Y *myX;
};


int X::foo( const char * const key )
{
    X *myX = NULL; // illegal.
}

static cast and static cast references are not working as I had intended.

+1  A: 

If maxSize is a normal member of class X then you can't access it that way. You would have to pass it as another parameter to the function.

If maxSize is a static member of the class, then that code should work.

If this wasn't what you were asking, then you need to clarify your question and maybe add some more code showing what you're having trouble with.


Edit:

In your new example, the line you marked "illegal" would actually compile the way you've written it. (It's declaring a local X pointer named myX which only exists inside that function.)

But I'm guessing you actually meant:

int X::foo( const char * const key )
{
    myX = NULL;
}

And that would fail because myX is not a static variable. Static functions cannot access normal member variables. They can only access static variables.

You would need to revise your design:

  • Either make myX a static member of X if that is appropriate in your program.
  • Or make X::foo a non-static member function.
  • Or add another parameter to X::foo through which you can get access to myX. There would be several ways depending how you want to design things. Here's an example: int X::foo( const char * const key, X *& theXpointer )
TheUndeadFish
A: 

You can't access member data in a static function. It only has access to static data and other static functions. If you need a class function to act on members of an object, you shouldn't declare that function static, or you need to pass in that object as a parameter to the static function.

Bill
A: 

I'm not sure what you mean when you say "access class object types." Your code as you wrote it will allow you to use the X type in the static X::foo function (of course, you have to return a value from it since you have declared that it returns an int).

As you've written it, you are declaring a pointer to an instance of X and from your code I'm not sure if that's what you've intended or what you will do with that pointer.

Ron Pihlgren