Reputation: 3247
In the Bird class, there is one virtual function canFly() which is implemented in two classes: Parrot and Crow. G is a global class which remembers the no. of birds (i.e. either Crow or parrot) and then printBirds() prints the birds' ability to fly.
But i am getting some error due to undefined references. Can somebody please explain this. Why are these errors occuring and how to rectify the program to remove errors.
#include <iostream>
using namespace std;
class Bird
{
bool abilityToFly;
public:
Bird()
{
abilityToFly=0;
}
bool getAbility()
{
return abilityToFly;
}
void setAbility(bool x)
{
abilityToFly=x;
}
virtual void canFly()
{
abilityToFly=0;
}
};
class Crow: public Bird
{
public:
void canFly()
{
setAbility(1);
}
};
class Parrot: public Bird
{
public:
void canFly()
{
setAbility(1);
}
};
class G
{
public:
static int numBirds;
static Bird *b[10];
static void addBird(Bird bird)
{
b[numBirds]= &bird;
numBirds++;
if (numBirds>10)
cout<<"Error in program";
}
static void printBirds()
{
for(int i=0;i<numBirds;i++)
{
cout<<"Bird "<<i<<"'s ability to fly"<<b[i]->getAbility();
}
}
};
int G::numBirds=0;
int main()
{
Parrot p;
p.canFly();
Crow c;
c.canFly();
G::addBird(p);
G::addBird(c);
G::printBirds();
return 0;
}
The errors are:
In function `main':
undefined reference to `G::b'
undefined reference to `G::b'
undefined reference to `G::b'
The link to the code is: http://codepad.org/Mjpu4wFv
Upvotes: 0
Views: 146
Reputation: 8288
G::b is a static data member, you should initialize it.
int G::numBirds=0;
Bird * G::b[10];
Another error in your code, you should modify as follows:
static void addBird(Bird* bird)
{
b[numBirds] = bird;
numBirds++;
if (numBirds>10)
cout<<"Error in program";
}
and in main():
G::addBird(&p);
G::addBird(&c);
Otherwise the parameter you transfer in addBird is a temporary one, but you give the address of the temporary parameter to G::b[]
Upvotes: 6