Initialize

Say you have a class polygon and it has a member default_length and you want to initialize that value without explicitly using a constructor. Is this code legal and what is it doing?
 
int Polygon::default_length (1);


This way all Polygon objects have a default_length member that is 1.

Right?
That is only legal if default_length is a static member. It is not legal for nonstatic members.

If it's static, though -- yeah, that's exactly right.

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

EDIT:

Note that you would typically put that line in the "polygon.cpp" file or whatever source file implements Polygon, in the global scope (or in the scope of whatever namespace Polygon is in)

Additionally, you would need to declare the variable in the Polygon class.

1
2
3
4
5
6
7
8
9
10
// polygon.h
class Polygon
{
...
  static int default_length;
};

// polygon.cpp
#include "polygon.h"
int Polygon::default_length(1);


Alternatively, for integer types only you can initialize them right in the class itself:

1
2
3
4
5
class Polygon
{
...
  static int default_length = 1;
};
Last edited on
Thank you. However, if it is static then the derived classes from polygon will not inherit that member correct?
Sure they do.

If your default_length member is public or protected, any child classes will be able to access it.
Topic archived. No new replies allowed.