c++listiteratorconst-iterator

Cannot convert 'this' pointer from 'const Bullet' to 'Bullet &'


I am trying to use a list for my bullets. Whenever I run my update bullet code it gives me this error:

Error 1 error C2662: 'Bullet::detectCollision' : cannot convert 'this' pointer from 'const Bullet' to 'Bullet &'

my list:

std::list<Bullet> bullet_list;

my update code:

std::list<Bullet>::const_iterator cIter;
    for ( cIter = bullet_list.begin( ); cIter != bullet_list.end( ); cIter++ )
    {
        if((*cIter).detectCollision(monster.position,monster.getHeight(),monster.getWidth()))
        {
//Do stuff here
        }
        if ((*cIter).detectCollision(boss.getPosition(),boss.getHeight(),boss.getWidth()))
        {
//Do stuff here
        }
    }

my detect collision code:

bool Bullet::detectCollision(Vector objTwo,int heightT,int widthT)
{
if(position.getVectorX() >= objTwo.getVectorX() - (widthT/2) && position.getVectorX() <= objTwo.getVectorX() + (widthT/2)
    && position.getVectorY() >= objTwo.getVectorY() - (widthT/2)&& position.getVectorY() <= objTwo.getVectorY() + (heightT/2) && alive)
{
    return false;
}
return true;
}

Solution

  • You need to declare detectCollision as const.

    bool Bullet::detectCollision(Vector objTwo,int heightT,int widthT) const
    

    When you don't, it's trying to do a conversion so it can call a non-const function on a const reference but it's not allowed.