Newbie help using static variables

  • Thread starter Ramprasad A Padmanabhan
  • Start date
R

Ramprasad A Padmanabhan

Hi all,
I am a C & perl programmer trying my hand at c++. Can someone tell
whats wrong with this


--------------------------------------------------
using namespace std;
#include <iostream>

class Myobj {
public :
static int count;
Myobj(){
cout <<"Creating a new obj \n";
count++;
}
};

int main() {
Myobj *x,y;
x = new Myobj();
exit(0);
}

------------------------------------------------------------

My program does not compile on linux I get an error

g++ n4.cpp -o n4
/tmp/ccLKO0S2.o(.gnu.linkonce.t._ZN5MyobjC1Ev+0x1d): In function
`Myobj::Myobj[in-charge]()':
: undefined reference to `Myobj::count'
collect2: ld returned 1 exit status
make: *** [n4] Error 1


Thanks
Ram
 
S

Sumit Rajan

Ramprasad said:
Hi all,
I am a C & perl programmer trying my hand at c++. Can someone tell
whats wrong with this


--------------------------------------------------
using namespace std;
#include <iostream>

class Myobj {
public :
static int count;
Myobj(){
cout <<"Creating a new obj \n";
count++;
}
};

You need to define count:

int Myobj::count = 0;
int main() {
Myobj *x,y;

Why not just:
Myobj x;

You may want to use return instead of exit.
}

------------------------------------------------------------

My program does not compile on linux I get an error

g++ n4.cpp -o n4
/tmp/ccLKO0S2.o(.gnu.linkonce.t._ZN5MyobjC1Ev+0x1d): In function
`Myobj::Myobj[in-charge]()':
: undefined reference to `Myobj::count'
collect2: ld returned 1 exit status
make: *** [n4] Error 1


Thanks
Ram


Regards,
Sumit.
 

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
474,199
Messages
2,571,045
Members
47,643
Latest member
ashutoshjha_1101

Latest Threads

Top