Why can't a public member function see a private data?

P

pembed2003

Hi all,
How come the following won't compile?

#include <iostream>

using std::cout;
using std::endl;

class A{
private:
static A* a;
A(){}
public:
static A* getA(){
if(!a) a = new A;
return a;
}
};

int main(int,char**){
A* p = A::getA(); // ERROR
}

It says something like:

.... in getA():test.cc: undefined reference to 'A::a'

It's a linking error but I don't understand why. Can someone explain to me? Thanks!
 
P

Phlip

pembed2003 said:
How come the following won't compile?

'private' has nothing to do with it. You could make all public and get the
same error.
#include <iostream>

using std::cout;
using std::endl;

class A{
private:
static A* a;

C++ uses declarations and definitions. The above declares 'a' but gives it
no home storage spot - its definition.
A(){}
public:
static A* getA(){
if(!a) a = new A;
return a;
}
};

Give 'a' a place to live like this:

A * A::a;
int main(int,char**){
A* p = A::getA(); // ERROR
}

It says something like:

... in getA():test.cc: undefined reference to 'A::a'

The situation is similar to saying 'extern int q;', but never saying 'int
q;' in global scope anywhere. All declaration and no definition. Static data
members need definitions too.
 
R

Roberto Diaz

you have to reserve storage for 'a', add something like this:

A *A::a = 0;
 
D

David Harmon

On 4 Aug 2004 22:47:24 -0700 in comp.lang.c++, (e-mail address removed)
(pembed2003) wrote,
It says something like:

... in getA():test.cc: undefined reference to 'A::a'

It's a linking error but I don't understand why.

This issue is covered in Marshall Cline's C++ FAQ. See the topic
"[10.10] Why are classes with static data members getting linker
errors?" It is always good to check the FAQ before posting. You can
get the FAQ at:
http://www.parashift.com/c++-faq-lite/
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,007
Latest member
obedient dusk

Latest Threads

Top