Albert Lazaro de Lara
Albert Lazaro de Lara

Reputation: 2710

C++ autoload default constructor on object property

I'm new in C++ programming and I have the problem that the WorldMapState class automatically creates a new object of the property tile_map (TileMap). If TileMap has no arguments on constructor there is no problem, but I added three arguments and WorldMapState automatically tries to create an object with empty constructor. Why C++ works in that way? How can I solve the problem?

#pragma once
#include <SFML\Graphics.hpp>

namespace SaGa {

    class TileMap : public sf::Drawable, public sf::Transformable
    {
    public:
        TileMap(unsigned int width, unsigned int height, unsigned int tileSize);
        bool load(const std::string& tileset, sf::Vector2u tileSize, const int* tiles);
        void setSprite(unsigned int value, unsigned int x, unsigned int y);
    private:
        virtual void draw(sf::RenderTarget& target, sf::RenderStates states) const;

        sf::VertexArray m_vertices;
        sf::Texture m_tileset;

        unsigned int _width;
        unsigned int _height;
        unsigned int _tileSize;
    };
}

Main Class

#pragma once

#include <SFML\Graphics.hpp>
#include "State.hpp"
#include "Game.hpp"
#include "TileMap.hpp"
#include <vector>

namespace SaGa
{
    class WorldMapState : public State
    {
    public:
        WorldMapState(GameDataRef data);

        void Init();
        void HandleInput();
        void Update(float dt);
        void Draw(float dt);

    private:
        GameDataRef _data;
        //sf::Texture _tilemap;
        //std::vector<sf::Sprite> _tiles;
        TileMap _tilemap;
    };
}

Upvotes: 2

Views: 71

Answers (1)

Nikos C.
Nikos C.

Reputation: 51910

If TileMap has no arguments on constructor there is no problem, but I added three arguments and WorldMapState automatically tries to create an object with empty constructor. Why C++ works in that way?

Because your TileMap constructor needs 3 parameters. They're not optional. Either add another constructor to TileMap that takes no arguments:

public:
    TileMap();
    TileMap(unsigned int width, unsigned int height, unsigned int tileSize);

Or use default values for the existing constuctor:

public:
    TileMap(unsigned int width = 0, unsigned int height = 0, unsigned int tileSize = 0);

Or initialize _tilemap correctly by using 3 parameters using either inline initialization:

private:
    // ...
    TileMap _tilemap{0, 0, 0};

Or using a constructor initializer list in the constructor's definition in the cpp file:

WorldMapState::WorldMapState(GameDataRef data)
    : _tilemap(0, 0, 0)
{
    // ...
}

Pass values that are suitable in your case, of course.

Upvotes: 2

Related Questions