Problem with static varibale and default constructor defnied in polymorphic class

Dear All users;
I am new to C++ programming.
I would be appreciative if you help me with solving my problem.
I have a problem with adding some lines to tutorial for polymorphism section. I defined a protected static variable in Polygon class to count Polygon objects I have. I did like this:

// virtual members
#include <iostream>
using namespace std;


class Polygon{
protected:
double width, height;
static int n;
public:
Polygon(){n++;}
void set_values (int a, int b)
{ width=a; height=b; }
virtual int area ()
{ return 0; }
};
.
.
.
=====
I got this error:

/tmp/ccvtHuuA.o: In function `Polygon::Polygon()':
virtual.cpp:(.text._ZN7PolygonC2Ev[_ZN7PolygonC5Ev]+0x15): undefined reference to `Polygon::n'
virtual.cpp:(.text._ZN7PolygonC2Ev[_ZN7PolygonC5Ev]+0x1e): undefined reference to `Polygon::n'
collect2: ld returned 1 exit status
=====
My OS is ubuntu 12.04.
Where is my error from?
closed account (2LzbRXSz)
That part of the program is working just fine for me. Can you post your full code please?

Also, you should use the code tags [ code] [ /code] (without the spaces) - it makes your code easier to read for the people on this site.
You just declared nbut didn't defined it.
You should define it like int Polygon::n;.

1
2
3
4
5
6
7
8
9
10
11
12
class Polygon{
protected:
double width, height;
static int n;
public:
Polygon(){n++;} 
void set_values (int a, int b)
{ width=a; height=b; }
virtual int area ()
{ return 0; }
};
int Polygon::n=0;
While,
Thanks to you, it works fines but why? If it is possible describe how this definition solve my problem or please refer me to a resource to study.
The codestatic int n;inside the class definition is just a declaration.
Static members of a class are not associated with the objects of the class: they are independent objects with static storage duration or regular functions defined in namespace scope, only once in the program.
(http://en.cppreference.com/w/cpp/language/static)

You should decide where you define n.The definition of n can only appear once in the whole program.Thus, the declaration inside the class definition can't be considered as a definition.
While,
Thank you for your reply.
Topic archived. No new replies allowed.