0

I have a copy constructor for a class Block

Block::Block(const Block& p_block):Drawable(p_block) {
}

which inherits from a class Drawable

Drawable::Drawable(const Drawable& p_drawable) {
    sprite = p_drawable.sprite;
    texture = p_drawable.texture;
    x = p_drawable.x;
    y = p_drawable.y;
}

I was using pointers to store the objects, but tried to switch to not using pointers, and now the sprites and textures get lost. I'm quite sure my use of references/pointers is terribly misinformed.

draw method:

void Room::draw(sf::RenderWindow &p_window) {
    for(auto& block : blocks) {
        block.draw(p_window);
    }
...
}

Can include any other code necessary. Just wondering if i'm doing something wrong in the copy constructor, or if i actually should be using pointers.


I'm also using this for collisions, not sure if something here might be causing problems.

struct sortBlocksByDistance {
    Drawable *drawable;
    sortBlocksByDistance(Drawable* p_drawable) {
        this->drawable = p_drawable;
    }
    bool operator () (Block* a, Block* b) {
        float adx = a->x - drawable->x,
        ady = a->y - drawable->y,
        adist = adx * adx + ady * ady;

        float bdx = b->x - drawable->x,
        bdy = b->y - drawable->y,
        bdist = bdx * bdx + bdy * bdy;

        return adist < bdist;
    }
};

std::vector<Block*> Room::detectCollisions(Drawable *p_drawable) {
    std::vector<Block*> hitBlocks;
    for(auto& block : blocks) {
        if(block.collidesWith(p_drawable)) {
            hitBlocks.push_back(&block);
        }
    }
    std::sort(hitBlocks.begin(), hitBlocks.end(), sortBlocksByDistance(p_drawable));
    return hitBlocks;
};

std::vector<Block*> collisions = detectCollisions(player);
player->solveCollisions(collisions);

void Drawable::solveCollisions(std::vector<Block*> p_blocks) {
    while(p_blocks.size()) {
        Block &block = *p_blocks.front();
        // x/y manipulation

        // pop front
        p_blocks.front() = std::move(p_blocks.back());
        p_blocks.pop_back();
    }
};
nvoigt
  • 75,013
  • 26
  • 93
  • 142
Evan Ward
  • 1,371
  • 2
  • 11
  • 23
  • 3
    The copy constructor looks fine. Did you ensure you are implementing the [Rule of Three](http://stackoverflow.com/questions/4172722/what-is-the-rule-of-three) properly? Also [slicing](http://stackoverflow.com/questions/274626/what-is-object-slicing) is a common issue. – πάντα ῥεῖ Oct 21 '15 at 13:14
  • 1
    `std::vector` better should be `std::vector>` or `std::vector>`. – πάντα ῥεῖ Oct 21 '15 at 13:18
  • 2
    @πάνταῥεῖ Or better, the [rule of zero](https://rmf.io/cxx11/rule-of-zero/) ;) – vsoftco Oct 21 '15 at 13:26

0 Answers0