Im trying to make a game. Theres a player and he shoots bullets, and i was told whats wrong is it is making a shallow copy instead of a deep copy even though i researched this i cannot completely understand it. This is my attempt however i know it is wrong in some way because whenever i call the fire() method, the program crashes. I am VERY desperate i have been trying to solve this for a very long time and would appreciate any help!
Bullet Class:
#include "Bullet.h"
Bullet::Bullet()
{
ptr = NULL;
}
Bullet::~Bullet() {
delete ptr;
ptr = NULL;
}
Bullet& Bullet::operator= (Bullet const& f) {
if ( this != &f ) {
delete ptr;
ptr=new char[strlen(f.ptr)+1];
strcpy(ptr,f.ptr);
}
return *this;
}
Bullet::Bullet(const char *p) {
ptr=new char[strlen(p)+1];
strcpy(ptr,p);
}
Bullet::Bullet ( Bullet const& f) {
ptr=new char[strlen(f.ptr)+1];
strcpy(ptr,f.ptr);
}
Bullet::Bullet(int startX, int startY, int moveX, int moveY)
{
startingX = startX;
startingY = startY;
x = 0;
y = 0;
dx = moveX;
dy = moveY;
Extra ex;
}
int Bullet::getX()
{
return x;
}
int Bullet::getY()
{
return y;
}
int Bullet::getDx()
{
return dx;
}
int Bullet::getDy()
{
return dy;
}
int Bullet::getStartingX()
{
return startingX;
}
int Bullet::getStartingY()
{
return startingY;
}
void Bullet::move()
{
x += dx;
y += dy;
}
void Bullet::show(SDL_Surface *bullet, SDL_Surface *screen, SDL_Rect camera)
{
//Show the bullet
ex.apply_surface( (startingX - camera.x) + x, (startingY - camera.y) + y, bullet, screen );
}
fire() method:
#include "Dot.h"
using namespace std;
Dot::Dot()
{
//Initialize the offsets
mousex = 0;
mousey = 0;
angle = 0;
imageOffsetX = 15;
imageOffsetY = 15;
dx = 1;
dy = 1;
bullets = 20;
velocity = 3;
box.x = 32;
box.y = 32;
box.w = 20;
box.h = 20;
TYPE_WOOD = 0;
TYPE_ROCK = 1;
TOTAL_TILES = 2304;
//Bullets
vector<Bullet> playerBullets;
//Path to extra function
Extra ex;
//Initialize the velocity
xVel = 0;
yVel = 0;
}
void Dot::fire()
{
if( bullets > 0 )
{
if (angle == 0){
playerBullets.push_back( Bullet(box.x, box.y, 5, 0) );
}else if(angle == 90){
playerBullets.push_back( Bullet(box.x, box.y, 0, -5) );
}else if(angle == 180){
playerBullets.push_back( Bullet(box.x, box.y, -5, 0) );
}else if(angle == 270){
playerBullets.push_back( Bullet(box.x, box.y, 0, 5) );
}
}
}