[Newbie Question] Static members

M

Manuel

Hi!
Anyone can explain me why this work:

--------------------------
class Rect
{
public:
Rect()
{num ++;}

~Rect()
{num --;}

static void pippo(){num ++;};

protected:
static int num;

};
int num = 0;

main(){}
-------------------------

and this not work?

-------------------------
class Rect
{
public:
Rect()
{num ++;}

~Rect()
{num --;}

static void pippo();

protected:
static int num;

};
int num = 0;
void Rect::pippo() {num ++;}
main(){}
 
M

Marchello

and this not work?
-------------------------
class Rect
{
public:
Rect()
{num ++;}

~Rect()
{num --;}

static void pippo();

protected:
static int num;

};
int num = 0; // Maybe errors occurs here ?!
void Rect::pippo() {num ++;}
main(){}

try to write:
int Rect::num = 0;
 
J

Jim Langston

Manuel said:
Hi!
Anyone can explain me why this work:

--------------------------
class Rect
{
public:
Rect()
{num ++;}

~Rect()
{num --;}

static void pippo(){num ++;};

protected:
static int num;

};
int num = 0;

main(){}
-------------------------

and this not work?

-------------------------
class Rect
{
public:
Rect()
{num ++;}

~Rect()
{num --;}

static void pippo();

protected:
static int num;

};
int num = 0;
void Rect::pippo() {num ++;}
main(){}

Actually, it's fairly simple. Rect::pippo() is static. Which means it's
only supposed to be used on static variables. They have no this pointer.
Neighter of those should work.

change num to static and it should work.

static int num;

then outside the class

int Rect::num = 0;

I can not tell you why your first version compiled. It shouldn't of as far
as I'm aware.
 
M

majianan

I have seen the first program in the <Effective C++> : Item 14:Make
sure base classes have virtual destructors.
 
M

Manuel

majianan said:
I have seen the first program in the <Effective C++> : Item 14:Make
sure base classes have virtual destructors.

What's <Effective C++> ?
A template for debug?
 
M

Manuel

Jim said:
change num to static and it should work.

static int num;

This was already done...or you mean I should write this in some other
places?
then outside the class

int Rect::num = 0;


Yes. This was the error!
Thanks,

Manuel
 
B

bvatsa

U must use Class scope, while acessing Static class members,...
I think u need to brush-up c++ once...
 

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

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,053
Latest member
BrodieSola

Latest Threads

Top