Problem with static varibale and default constructor defnied in polymorphic class

May 10, 2015 at 7:28pm
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?
May 10, 2015 at 7:38pm
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.
May 11, 2015 at 3:37am
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;
May 11, 2015 at 6:11pm
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.
May 18, 2015 at 2:40am
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.
May 18, 2015 at 4:08pm
While,
Thank you for your reply.
Topic archived. No new replies allowed.