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.
The class
std::vectorrequires 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
vectorin it’s constructor call, so that it will use that instance instead of trying to default-construct one:If the vector that you are using to store
Players is a member variable, you’ll need to pass it the defaultPlayerto use in the initialiser list: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 functionresizewhen called with a single argument. If you use the constructor that takes iterators or aconst Allocator&, or if you useresizewith the second argument, then you don’t need a DC.