Mark Eastwood
Mark Eastwood

Reputation: 27

C++ Constructor won't pass string - no constructor defined

I am trying to create an object of "Player" inside "PlayerManager" and I am getting the error in VS2010:

Error 1 error C2512: 'Player::Player' : no appropriate default constructor available c:\program files (x86)\microsoft visual studio 10.0\vc\include\memory 631 1 Server

Player.h:

#ifndef _PLAYER_H
#define _PLAYER_H

#include <iostream>
#include <string>

using namespace std;

class Player
{
public:
    Player(const string &name);
~Player(void);


private:
    string name_;
};

#endif

Here is the constructor in Player.cpp:

Player::Player(const string &name)
{

}

PlayerManager.h:

'#ifndef _PLAYERMANAGER_H
#define _PLAYERMANAGER_H

#include <string>
#include <vector>
#include <iostream>

#include "Player.h"

using namespace std;

class PlayerManager
{
public:
    PlayerManager(void);
    ~PlayerManager(void);

private:
    vector<Player> players;
};

#endif'

Here is where I create the object in PlayerManager.cpp:

PlayerManager::PlayerManager(void)
{
        Player test("Hello");
        players.resize(1000);
    for(int i=0; i < 960; i++){
        players.push_back(test);
    }
}

I don't understand why it is ignoring the string "Hello", I have tried creating a string object but gives same error.

I have also tried without adding the const & in the constructor but gives same error.

Any help would be appreciated, spend hours searching for an answer. Apologies if the layout is incorrect as this is my first time asking a question.

Upvotes: 1

Views: 1020

Answers (1)

Seth Carnegie
Seth Carnegie

Reputation: 75130

The class std::vector requires that the class you use it with has a default constructor1. You'll need to provide one for your class.

If you really don't want to provide one, you can give an instance of your class to vector in it's constructor call, so that it will use that instance instead of trying to default-construct one:

vector v(initialsize, Player("")); // or you can pass whatever string you want the default item to have

If the vector that you are using to store Players is a member variable, you'll need to pass it the default Player to use in the initialiser list:

PlayerManager::PlayerManager() : players(initialsize, Player("")) { // assuming the vector is named players
    .... 
}


1 As R. Martinho Fernandes and Kerrek SB have pointed out in the comments, a default constructor is only required for this particular constructor of vector (the one that takes an initial size and when you don't give it a default instance) and the member function resize when called with a single argument. If you use the constructor that takes iterators or a const Allocator&, or if you use resize with the second argument, then you don't need a DC.

Upvotes: 9

Related Questions