View Single Post
Old 05-09-2004, 03:20 AM   #1 (permalink)
cliche
Rookie
 
cliche's Avatar
 
Location: Oxford, UK
[c++] classes and static const arrays

I'm relatively new to C++ (but not programming in general), and I'm trying to use classes with static arrays as members like so:

Base class (eg dog) with function print_data() which prints data from an array.
Derived classes (eg spaniel, collie) with static const data in the array. So all collies have the same, and all spaniels have the same - but everything is printed via dog::print_data().

eg (and this code doesn't work):
Code:
class dog
{
 public:
  void print_data();
};


class collie : public dog
{
 public:
  static const int array[];
};


class spaniel : public dog
{
 public:
  static const int array[];
};


const int spaniel::array[2]={111,222};
const int collie::array[2]={333,444};

void dog::print_data()
{
  cout << array[0] << "\n";
  cout << array[1] << "\n";
}
Quite reasonably the compiler has trouble with the fact that I could declare something as a 'dog', which then wouldn't have an array for print_data(). How do I convince it that it should print the data for the correct breed, without just duplicating the function for each breed? Or is this not possible?

Thanks for any input.


EDIT: Realised this is going to cause problems with any vars (not just arrays). I used arrays as the example as I'd been having such trouble initialising them for the class - ie you can't use 'static const int array[2]={111,222};' as part of a class definition.

EDIT2: Removed the bloody smilies to make Knifemissile's later comment look a bit random :)
__________________
I can't understand why people are frightened of new ideas. I'm frightened of the old ones. -- John Cage (1912 - 1992)

Last edited by cliche; 05-09-2004 at 11:00 PM..
cliche is offline  
 

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37