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
addBird()is broken. change the function to take a reference as parameter.canFly()could you explain it?addBird()is broken?addBird()is broken becaue you are passingbirdby value as the funtion's parameter, it provides a local temp value, which will be freed after the funtion ends, and in the function, you uses this temp value's addressb[numBirds]= &bird;so this will cause undefined behaviour