0

I'm trying to add an object to a vector, but it's not working.

Code:

class GameClass{
public:
        void makeNewPlayer(int isItBad){
            if (isItBad==0){
                goodPlayers.push_back(PlayerClass());
            }
        }
private:
        vector<PlayerClass> badPlayers;
        vector<PlayerClass> goodPlayers;
};


class PlayerClass{ 
public:
    PlayerClass(int badStatus){
        myLocation[0]=rand()%(N-2)+1;
        myLocation[1]=rand()%(N-2)+1;
        isBad=badStatus;
    }

   void setMyLocation(int x, int y){
    myLocation[0]=x;
    myLocation[1]=y;
    }
    void getMyLocation(int *targetLoc){
    targetLoc[0]=myLocation[0];
    targetLoc[1]=myLocation[1];
    }
private:
    int myLocation[2];
    int isBad=1;
};

Error

no matching function for call to 'PlayerClass::PlayerClass()'|

From this line:

     goodPlayers.push_back(PlayerClass());

edit: how can i make it default constructor???

1
  • You'll need a public default constructor PlayerClass() declared and defined to get this working. Commented Aug 20, 2014 at 18:08

1 Answer 1

3

You get that error because you do not have a default constructor.. You have a custom constructor hence the default constructor is not automatically supplied.

So you need to pass a value for badstatus something like:

goodPlayers.push_back(PlayerClass(4));

You can make default by making the badstatus as default argument, example:

PlayerClass(int badStatus=4){
        myLocation[0]=rand()%(N-2)+1;
        myLocation[1]=rand()%(N-2)+1;
        isBad=badStatus;
    }

Now even if you don't supply the argument of 4, it will work fine.. Give the badstatus a default value.

Suggestion: Always ensure that the default constructor is there for the class. Even if you forgot to pass in the argument, you can still instantiate the object from the class.

In your case, instead of setting int isBad=1; change to int isBad; and add the "=1" to

PlayerClass(int badStatus=1){
        myLocation[0]=rand()%(N-2)+1;
        myLocation[1]=rand()%(N-2)+1;
        isBad=badStatus;
    }
Sign up to request clarification or add additional context in comments.

3 Comments

'overrides the default constructor' isn't entirely correctly worded IMHO.
how can i make it default?
@JohnnyF 'how can i make it default?' You can provide a default value for the parameter in the declaration.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.