I've been working in inheritance in C++ for a while now - I know the basics, at least. What I'm trying to do now is inherit a Hare class from a generic Animal class. The Animal class has speed, viciousness, laziness, name, and symbol attributes, which are normally initialized when I create a Hare object:
Hare hare1(0.8,0.2,"Speedy",'@');
Now, what I want to do is have the Hare class contain two private static variables: speed and viciousness. Since these will always be the same in every Hare object, I want to have predefined values for speed/viciousness so their values don't have to be specified when creating the Hare object. So, what I do is this:
Hare hare1("Speedy",'@');
And in the Hare constructor, I initialize the static values (which are declared in the .h file). That's fine. But when I send off the two static values and the given name/symbol values tot he Animal constructor, I get 4 errors, 2 each about no reference to the static values. I've got no idea what to do - any help?
Here is the code I have for Animal and Hare:
Animal.h
class Animal {
public:
/* Member functions */
/* Purpose: constructor; initializes animal's attributes.
* Takes: values for speed, viciousness, name, and symbol
* Returns: nothing
*/
Animal(double speed, double viciousness, string name, char symbol);
Animal.cpp
Animal::Animal(double inSpeed, double inViciousness, string inName,
char inSymbol) {
speed = inSpeed;
//The animal's laziness is always equal to half it's speed
laziness = speed / 2;
viciousness = inViciousness;
position = 0; //The animal always starts at position 0 (start of race)
name = inName;
symbol = inSymbol;
// srand ( time(NULL) ); //Initialize random number generator
} //End Animal constructor
Hare.h
#include "Animal.h"
class Hare : public Animal {
public:
/* Member functions */
//Constructor
Hare(string name, char symbol);
private:
/* Attributes */
static double speed;
static double viciousness;
//No extra attributes needed; inherited from Animal
}; //End class Hare
Hare.cpp
//The Hare constructor calls the Animal constructor to do the work.
Hare::Hare(string name, char symbol) :
Animal(speed, viciousness, name, symbol) {
speed = 0.8;
viciousness = 0.2;
//No need to do anything here.
} //End Hare Constructor
And these are the errors I get:
c:\documents and settings\grant palin\my documents\school\comp160\race\hare.o(.text+0x72):hare.cpp: undefined reference to `Hare::viciousness'
c:\documents and settings\grant palin\my documents\school\comp160\race\hare.o(.text+0x7e):hare.cpp: undefined reference to `Hare::speed'
c:\documents and settings\grant palin\my documents\school\comp160\race\hare.o(.text+0xdd):hare.cpp: undefined reference to `Hare::speed'
c:\documents and settings\grant palin\my documents\school\comp160\race\hare.o(.text+0xe9):hare.cpp: undefined reference to `Hare::viciousness'
Thanks for any help.
Grant Palin