Accessing Member Values from Static Member Function

Is there a way to access the value of a member variable from within a static member function?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class MyClass
  public:
    MyClass();
    ~MyClass();
    static void *Print();
  private:
    string hello;
};

MyClass::MyClass()
{
    hello = "Hello World";
}

...

void *MyClass::Print()
{
    cout << hello << endl; // Trying to access data stored in "hello" variable
}


The tutorials that I have read say that static functions can only access static members. Here's one of the tutorials: http://msdn.microsoft.com/en-us/library/yyh8hetw.aspx

So I would have to declare my member variable like this:
1
2
3
4
5
6
7
8
9
10
class MyClass
  public:
    MyClass();
    ~MyClass();
    static void *Print();
  private:
    static string hello;
};

string MyClass::hello = "Hello World";


But I want to be able to change the value of "hello" from within the class. I have tried the following two methods that don't work:
1
2
3
4
MyClass::MyClass()
{
    string MyClass::hello = "Hello World";
}


1
2
3
4
5
6
7
8
9
int SetString()
{
    string MyClass::hello = "Hello World";
}

MyClass::MyClass()
{
    SetString();
}


But both return this error:
error: invalid use of qualified-name ‘MyClass::hello’
Static method may have access only to static members
Deluge wrote:
The tutorials that I have read say that static functions can only access static members.


So how do I create a static member and change its value from within a class?
I think what ur trying to do is to access a normal variable that can differ per class with a static function. But that's not where static functions are for, you need a regular class function for that.
http://ubuntuforums.org/showthread.php?p=9362621

Got figured out what I wanted to do:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#include <iostream>
using namespace std;

class MyClass
{
  public:
    MyClass();
    ~MyClass();
    void SetString();
  private:
    static string hello;
};

string MyClass::hello("Hello World");

MyClass::MyClass()
{
    SetString();
    cout << hello << endl;
}

MyClass::~MyClass()
{
}

void MyClass::SetString()
{
    hello = "Hello World";
}

int main()
{
    MyClass test;
    return 0;
}
Last edited on
Topic archived. No new replies allowed.