C ++ - no suitable default constructor

I have problems with a very simple program. It produces errors:

error C2512: 'Player' : no appropriate default constructor available

IntelliSense: no default constructor exists for class "Player"

I have a feeling that this is due to the declaration of the Player class as a private variable in Game.h, but I do not understand why. Any help would be greatly appreciated.

Game.h

#pragma once
#include "Player.h"

class Game
{
public:
    Game(void);
    void start(void);
    ~Game(void);
private:
    Player player;
};

Game.cpp

#include "Game.h"

Game::Game(void)
{
    Player p(100);

    player = p;
}

void Game::start()
{
    ...
}

Game::~Game(void)
{
}

Player.h

#pragma once
class Player
{
public:
    Player(int);
    ~Player(void);

private:
    int wallet;
};

Player.cpp

#include "Player.h"
#include <iostream>

using namespace std;

Player::Player(int walletAmount)
{
    wallet = walletAmount;
}

Player::~Player(void)
{
}
+4
source share
4 answers

Unlike C #, this is an ad;

Player player;

... is an instance of a type Player, which means that by the time you assign it inside the constructor, it was already constructed without a parameter.

, , Player , , ;

Game::Game(void) : player(100)
{
...

..., Player , no-parameter .

+13

Game, player . player , :

Game::Game() : player(100)
{
    ...
}
+6

Only Player::Player(int)exists, so you need to initialize the player inGame::Game()

Game::Game(void)
    : player( 100 )
{
}
+5
source

In the general case - not in this case - an error

no appropriate default constructor available

may also occur if you forget to include the header file for the associated object.

This happened to me, so I wanted to add this solution here.

+3
source

All Articles