Take the 2-minute tour ×

I'm working on a project now and I am confused on how to approach this.

class Unit: public Entity {
   string Name;
   int HP;
   int MP;
   int Agi;
   int Spr;
   int Def;
   int Atk;
   int Lvl;
   int Exp;
   std::vector<int> states;
   string unitType;
      int GetHP() {return HP};
      int GetMP() {return MP};
      int GetAgi() {return Agi};
      int GetSpr() {return Spr};
      int GetDef() {return Def};
      int GetAtk() {return Atk};
      int GetLvl() {return Lvl};
      int GetExp() {return Exp};
      std::vector<int>& GetStates() {return &states};
      string GetUnitType() {return unitType};
      virtual void SetHP(int newValue);
      virtual void SetMP(int newValue);
      virtual void SetAgi(int newValue);
      virtual void SetSpr(int newValue);
      virtual void SetDef(int newValue);
      virtual void SetAtk(int newValue);
      virtual void SetLvl(int newValue);
      virtual void SetExp(int newValue);

I need to return a reference to "std::vector states" so that I can iterate through it and look for values. I believe I should be using a Set because I only have one value and there cannot be repeats, but I'll save that for later. Is the "std::vector& GetStates() {return &states}" correct? Should it be changed to "std::vector& const GetStates() {return &states}" or am I completely off? I saw a post on here similar to this but it didn't specifically answer my question as they weren't using it in the same pretense as this.

share|improve this question

2 Answers 2

up vote 0 down vote accepted


No, there are syntax errors.

std::vector<int>& GetStates(){
    return states;

is correct.

Should it be changed to

That's up to you to decide. If you return non-const reference,, then whoever requested vector, will be able to change it. If you return const refernce, it makes sense to declare method as

const std::vector<int>& GetStates() const{
    return states;

Second const indicates that when you call this function, object's internal state won't change.

share|improve this answer
That makes sense, as I don't want it to be changeable when I use GetState. Since this is the core of it, GetState is only going to be used to check for its existence, where SetState will have the ability only to send data to be changed by the class to encapsulate changes within the class. At least that's how I see it working. –  k3524 Jun 23 '13 at 4:04

If states is a std::vector<int>, then &states is a std::vector<int>*, not a std::vector<int>&.

The descision to return a reference or not is made by the return type as provided in the function signature, not by the return statement in the implementation. Just do return states.

share|improve this answer

Your Answer


