Gerasimos Ragavanis Gerasimos Ragavanis - 3 months ago 24
C++ Question

extern vector created in constructor

I have a class Team and a class Ball and I create a vector in constructor of Team that is filled with objects of another class called Player. So I want to use this vector in the class Ball but even though I define it as extern (public) compiler keeps telling me that I have undefined reference to team that is my vector. Here follows the code of Team.cpp and Ball.cpp
Team.h

#define TEAM_H
#include <iostream>
#include <vector>
#include "Player.h"

using namespace std;
extern vector<Player> team;
class Team {
public:
Team();

void fillTeamVector(vector<Player>&);

private:
string teamName;
int faults;
int passes;
int goals;

};

#endif // TEAM_H


Team.cpp

#include "Team.h"
#include <vector>
#include <iostream>
#include "Player.h"
#include "Attacker.h"
#include "Defender.h"
#include "Ball.h"

Team::Team()
{
extern vector<Player> team;
fillTeamVector(team);
}

void Team::fillTeamVector(vector<Player>& team){

// do stuff and store them on vector team
}


And here follows the code for Ball.h note that I commented all the methods that don't affect the problem.

#ifndef BALL_H
#define BALL_H
#include "Player.h"

class Ball
{
public:
Ball();
Player* current;
Player* previous;

/*void setX_ball(int);
int getX_ball() const;
void setY_ball(int);
int getY_ball() const;*/
void assign();
//void changeCurrentToPrevious();
//void changeNextToCurrent(Player*);


private:
int X_ball;
int Y_ball;
};

#endif // BALL_H


Here is the code for Ball.cpp note that in method assign if I create a new (and obviously different vector of Player named team it will compile correctly)

#include "Ball.h"
#include "Team.h"
#include "Player.h"

extern vector<Player> team;

Ball::Ball()
: X_ball(2),
Y_ball(5)
{
current = NULL;
previous = NULL;

}

void Ball::assign(){
//vector<Player> team;
int x;
int y;
x=(team[0].getX())-X_ball;
y=(team[0].getY())-Y_ball;
int min=x+y;
int k=0;
for (int i=1; i<team.size(); i++){
x=(team[i].getX())-X_ball;
y=(team[i].getY())-Y_ball;
int sum=x+y;
if(sum<min){
k=i;
}
}
current = &team[k];
}

Answer

By doing

extern vector<Player> team;

you only declare the variable.

In one source file you must actually define the variable:

vector<Player> team;

Note the lack of extern in the definition.

Also note that this has to be done in the global scope, since you want a global variable. So it has to be defined outside of any functions or classes or namespaces.