By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
445,795 Members | 1,832 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 445,795 IT Pros & Developers. It's quick & easy.

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

P: n/a
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!
Jul 22 '05 #1
Share this Question
Share on Google+
3 Replies


P: n/a
pembed2003 wrote:
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.

--
Phlip
http://industrialxp.org/community/bi...UserInterfaces
Jul 22 '05 #2

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

A *A::a = 0;
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!

Jul 22 '05 #3

P: n/a
On 4 Aug 2004 22:47:24 -0700 in comp.lang.c++, pe********@yahoo.com
(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/

Jul 22 '05 #4

This discussion thread is closed

Replies have been disabled for this discussion.