Tilted Forum Project Discussion Community  

Go Back   Tilted Forum Project Discussion Community > Interests > Tilted Technology


 
 
LinkBack Thread Tools
Old 05-09-2004, 03:20 AM   #1 (permalink)
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  
Old 05-09-2004, 08:22 AM   #2 (permalink)
I am Winter Born
 
Pragma's Avatar
 
Location: Alexandria, VA
Static variables in classes don't work the same as static variables in C. A static variable in C++, declared as a class member, means that it is shared amongst all instances of the class.

Perhaps a better idea:
Code:
class Dog {
protected:
    int array[2];
public:
     inline void print_array() {
          cout << array[0] << endl << array[1] << endl;
     }
};

class Collie : public Dog {
public:
 Collie() { // override constructor
   array[0] = 5;
   array[1] = 6;
  }
};

class Spaniel : public Dog {
public:
  Spaniel() {
     array[0] = 7;
     array[1] = 8;
  }
};

int main() {
  Collie c;
  Spaniel s;
  c.print_array();
  s.print_array();
  return 0;
}
I'm still not really sure what your code even attempts to do, but hopefully that helps.
__________________
Eat antimatter, Posleen-boy!

Last edited by Pragma; 05-09-2004 at 08:29 AM..
Pragma is offline  
Old 05-09-2004, 10:12 AM   #3 (permalink)
Rookie
 
cliche's Avatar
 
Location: Oxford, UK
Quote:
Originally posted by Pragma
Static variables in classes don't work the same as static variables in C. A static variable in C++, declared as a class member, means that it is shared amongst all instances of the class.
Thanks for the help - but whilst your code does what I was trying to do, I'm quite keen to use C++ static variables (and, ideally, consts) so that there isn't an excessive waste of memory by having an extra copy of the array for each instance of Collie or Spaniel.
The only way I've found to do it so far is to declare the array as static within each derived class, and have a pointer variable in the base class which is set by the constructor function. Whilst that only wastes one 'int' per instance, it doesn't seem to take advantage of the const-ness of the data, and seems to be the Wrong Way of doing things...
__________________
I can't understand why people are frightened of new ideas. I'm frightened of the old ones. -- John Cage (1912 - 1992)
cliche is offline  
Old 05-09-2004, 01:45 PM   #4 (permalink)
I am Winter Born
 
Pragma's Avatar
 
Location: Alexandria, VA
What are you doing that requires it? The only real times you want to conserve memory are when you're doing massive applications. Saving 4 bytes of data per instance of the class is really nothing to worry about.

I'm still not understanding what you're doing - but you're confusing the hell out of me and are making things needlessly complex.
__________________
Eat antimatter, Posleen-boy!
Pragma is offline  
Old 05-09-2004, 06:02 PM   #5 (permalink)
 
KnifeMissile's Avatar
 
Location: Waterloo, Ontario
Pragma, that is a terrible attitude to have. You remind me of the story of the college instructor who was teaching his class how to write a linked list. When one of his students kindly remarked that his implementation leaked memory, he quickly stammered "Oh--well, no one worries about memory leaks, anymore..."

Of course, this is a total lie. People do worry about memory leaks, even in an age of cheap memory.

A similar lesson lies here. If each class has a constant table, there's no reason not to make it static...

So, to that end, try something like this:
Code:
class dog&#10{&#10private:  // it does no harm to explicitly declare access privilege...&#10&#10	/*&#10	I don't know how well you know C++ but there are a few things to note.&#10&#10	First, the const keyword modifies the thing to its _left_&#10	It's only a hack that, if there's nothing to its left, it modifies what's to its right.&#10&#10	Second, private member functions can be _defined_ by child classes, they&#10	just can't be _called_ by child classes.  See the distinction?&#10&#10	Thirdly, the "= 0" modifyier, if you've never seen it before, means&#10	that the function has no definition.  That means you can't actually make&#10	an instance of dog.  You must make instances which define the "= 0" member&#10	function--typically the children...&#10&#10	I hope this all makes sense to you!    */&#10	int const * get_array_data() = 0;&#10&#10public:&#10	void print_data();&#10};&#10&#10&#10class collie : public dog&#10{&#10private:&#10	static int const array[];  // there's no reason to make this public!&#10&#10	int const * get_array_data()&#10	{&#10		return array;&#10	}&#10};&#10&#10// keep your variables near the clases you define them in!&#10int const collie::array[2]={333,444};&#10&#10&#10class spaniel : public dog&#10{&#10private:&#10	static int const array[];  // there's no reason to make this public!&#10&#10	int const * get_array_data()&#10	{&#10		return array;&#10	}&#10};&#10&#10int const spaniel::array[2]={111,222};&#10&#10&#10void dog::print_data()&#10{&#10	int const * array = get_array_data();&#10	cout << array[0] << "\n";&#10	cout << array[1] << "\n";&#10}&#10&#10
On the surface, it looks like code is still duplicated, because a very similar get_array_data() must be implemented in each child class. However, this really isn't the case. Each get_array_data() function honestly does something different. They return a very specific table, depending on the class, so its "re-implementation" cannot be avoided. However, you can guarantee it will never be any more complicated than what you see. You are still reusing the print_data() function from the parent class, which may be very simple or very complicated, so all is well.

I'm tempted to say, from your question, cliche, that you have a good intuition for writing maintainable code. Then again, you admitted you're not a beginner programmer so, perhaps, that's why...


Oh--and, please, be careful with your smileys!




...edited for clarity and correctness...

Last edited by KnifeMissile; 05-13-2004 at 08:58 PM..
KnifeMissile is offline  
Old 05-09-2004, 06:23 PM   #6 (permalink)
I am Winter Born
 
Pragma's Avatar
 
Location: Alexandria, VA
My apologies, it is a bad attitude to have. I've been programming nonstop for the past several days on several projects and am not thinking quite right about everything.

Upon re-reading what cliche was intending to do, I agree with your implementation, KnifeMissle.
__________________
Eat antimatter, Posleen-boy!
Pragma is offline  
Old 05-09-2004, 10:59 PM   #7 (permalink)
Rookie
 
cliche's Avatar
 
Location: Oxford, UK
Thanks for the help, KnifeMissile, the compliment and the advice about smilies (I hadn't seen the option :) )
This is what I came up with myself - I'm not sure if it's just another instance of your result but it seems to work too:
Code:
class dog
{
 public:
  int const *numb;
  void print_data()
  { cout << *numb << "\n"; };
};


class collie : public dog
{
 public:
  static int const numb;
  collie(){dog::numb=&collie::int_numb;};
};
int const collie::int_numb=111;

class spaniel : public dog
{
 public:
  static int const int_numb;
  spaniel(){dog::numb=&spaniel::int_numb;};
};
int const spaniel::int_numb=555;
I've confusingly removed the arrays (when I realised it wasn't the fact it was an array that was the problem in the real code) and not bothered making int_numb private here. Any thoughts?

On reading around I've decided what I really was looking for was something like:
Code:
/* not valid C++ but I'd like it to be :) */
class dog
{
 public:
  virtual int numb;
  void print_data()
  { cout << numb << "\n"; };
};

class spaniel
{
public:
  static int const numb;
};

/* etc.... */
Thanks for all the help - C++ looks interesting once I can shoehorn it into my way of thinking...

EDIT to take Knifemissile's advice about const and data location... hope that's right!
__________________
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:08 PM..
cliche is offline  
Old 05-09-2004, 11:57 PM   #8 (permalink)
 
KnifeMissile's Avatar
 
Location: Waterloo, Ontario
Hey, I'm glad you're actually taking my advice seriously! Too many people just ignore me...

Actually, you simply implemented your initial second post, after Pragma's first response. It's not a bad idea except that mine uses up less memory. I was thinking of preemptively responding to this idea but I wasn't sure if you'd go with it...

Anyway, your solution uses a pointer per class instance where mine does no such thing. Plus, if you're just going to store an integer, you might as well just store the value instead of a pointer to the value, right?

Say, what's up with your new ultra-condensed indentation style?

Okay, I'm going to take a cheeky someone's advice and go to sleep...
KnifeMissile is offline  
Old 05-10-2004, 01:53 AM   #9 (permalink)
Rookie
 
cliche's Avatar
 
Location: Oxford, UK
(Once you've woken up) Just wondering exactly how your solution gets compiled (my previous programming experience was years of mostly 6502 and ARM assembler, C++ has started in earnest this week).
Does the compiler 'know' that your get_array_data function is essentially a constant? Is there any difference if it's declared static? (from my understanding this means one function is shared across all the instances)

If you're complaining about my indentation I should show you some of my old code Though people have remarked it's the heaviest-documented assembler they've seen...
__________________
I can't understand why people are frightened of new ideas. I'm frightened of the old ones. -- John Cage (1912 - 1992)
cliche is offline  
Old 05-10-2004, 12:01 PM   #10 (permalink)
 
KnifeMissile's Avatar
 
Location: Waterloo, Ontario
I just mean that your indentation style in your second code post is different than your first one. You seem to have changed styles for some reason...

Anyway, how my solution gets compiled is rather complicated. It makes use of a virtual function, so a virtual function table has to be created, so I don't think it can get inlined.

The problem is that the compiler can't know, at compile time, what function to call. For instance, take this piece of code:
Code:
void do_something_that_includes_printing(dog* dog_obj) {
	// do stuff...

	// how can the compiler know which dog this is?
	dog_obj->print_data();
}


int main() {
	dog* dog_obj = new collie();
	do_something_that_includes_printing(obj);
	delete dog_obj;

	dog_obj = new spaniel();  // reusing the pointer
	do_something_that_includes_printing(obj);
	delete dog_obj;

	return 0;
}
The only clue the compiler has as to what version of get_array_data() to use (in print_data(), used in do_something_that_includes_printing()) is the dog_obj pointer. However, it's only a pointer to the generic dog class, so it must make use of its virtual function table. This excludes the option of inlining it...

All member functions, static or not, are shared across instances of objects. It wouldn't be much of a function if it weren't (the whole point of a function is to reuse code!).
A static member function is a member function that lacks a this pointer. What that means is that, while it shares the same access privileges as other member functions, it can't access any member variables. Pretty funny, eh? Well, it makes more sense than it looks, at first...



...edited for clarity...

Last edited by KnifeMissile; 05-16-2004 at 02:56 PM..
KnifeMissile is offline  
Old 11-28-2007, 11:18 AM   #11 (permalink)
Upright
 
Code Reformat.

I thought KnifeMissile's code was worth reformatting, so I did it.

Quote:
Originally Posted by KnifeMissile
Pragma, that is a terrible attitude to have. You remind me of the story of the college instructor who was teaching his class how to write a linked list. When one of his students kindly remarked that his implementation leaked memory, he quickly stammered "Oh--well, no one worries about memory leaks, anymore..."

Of course, this is a total lie. People do worry about memory leaks, even in an age of cheap memory.

A similar lesson lies here. If each class has a constant table, there's no reason not to make it static...

So, to that end, try something like this:
Code:
class dog{
private:  // it does no harm to explicitly declare access privilege...

    /* I don't know how well you know C++ but there are a few 
        things to note. 

        First, the const keyword modifies the thing to its _left_  
        It's only a hack that, if there's nothing to its left, it
        modifies what's to its right.

	Second, private member functions can be _defined_ by 
        child classes, they just can't be _called_ by child classes.  
        See the distinction?

	Thirdly, the "= 0" modifier, if you've never seen it before, 
        means that the function has no definition.  That means you can't
        actually make an instance of dog.  You must make instances which
        define the "= 0" member function--typically the children...

	I hope this all makes sense to you!    */

int const * get_array_data() = 0;

public:
    void print_data();
};


class collie : public dog
{
private:
	static int const array[];  // there's no reason to make this public!

	int const * get_array_data()
	{
		return array;
	}
};

// keep your variables near the clases you define them in!
int const collie::array[2]={333,444};


class spaniel : public dog
{
private:
	static int const array[];  // there's no reason to make this public!

	int const * get_array_data()
	{
		return array;
	}
};

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


void dog::print_data()
{
	int const * array = get_array_data();
	cout << array[0] << "\n";
	cout << array[1] << "\n";
}
On the surface, it looks like code is still duplicated, because a very similar get_array_data() must be implemented in each child class. However, this really isn't the case. Each get_array_data() function honestly does something different. They return a very specific table, depending on the class, so its "re-implementation" cannot be avoided. However, you can guarantee it will never be any more complicated than what you see. You are still reusing the print_data() function from the parent class, which may be very simple or very complicated, so all is well.

I'm tempted to say, from your question, cliche, that you have a good intuition for writing maintainable code. Then again, you admitted you're not a beginner programmer so, perhaps, that's why...


Oh--and, please, be careful with your smileys!




...edited for clarity and correctness...

Last edited by SparkleSmite; 11-28-2007 at 11:32 AM.. Reason: I thought KnifeMissile's code was worth reformatting, so I did it.
SparkleSmite is offline  
 

Tags
arrays, classes, const, static


Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are On



All times are GMT -8. The time now is 08:59 AM.

Tilted Forum Project

Powered by vBulletin® Version 3.8.7
Copyright ©2000 - 2024, vBulletin Solutions, Inc.
Search Engine Optimization by vBSEO 3.6.0 PL2
© 2002-2012 Tilted Forum Project

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 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360