Need help with making a class for a Surface

Started by
1 comment, last by CraazyDave 12 years, 9 months ago
I need some input regarding a class I made for my game I'm trying to make in C++ with SDL.
The idea for the class is that it contains a SDL_Surface * that is created with its constructor and it should update the refcount of the surface for the user.

My header file:


#ifndef IMAGE_H
#define IMAGE_H

#include "SDL.h"

#include <string>

class Image
{
public:
Image();
Image(bool b, std::string filename);
~Image();
Image(const Image& other);
const Image& operator = (const Image& other);
SDL_Surface * getSurface();
void kill();

private:
SDL_Surface * picture;
SDL_Surface * opPicture;
};

#endif



The .cpp:


#include "Image.h"
#include "SDL.h"
#include <string>
#include <iostream>

using namespace std;

Image::Image()
{
picture = NULL;
opPicture = NULL;
}

Image::Image(bool b, string filename)
{
picture = SDL_LoadBMP(filename.c_str());

if(picture != NULL)
{
opPicture = SDL_DisplayFormat(picture);
SDL_FreeSurface(picture);
cout << "Picture is working" << endl;

if(b == true)
{
Uint32 transparent = *(Uint32*) opPicture -> pixels;
SDL_SetColorKey(opPicture, SDL_SRCCOLORKEY | SDL_RLEACCEL, transparent);
cout << "Transparent is working" << endl;
}
}
}

Image::Image(const Image & other)
{
other.opPicture -> refcount++;
}

const Image& Image::operator =(const Image& other)
{
if(this != &other)
{
SDL_FreeSurface(opPicture);
opPicture = other.opPicture;

other.opPicture -> refcount++;
}

return * this;
}

Image::~Image()
{
SDL_FreeSurface(opPicture);
}

void Image::kill()
{
delete this;
}

SDL_Surface * Image::getSurface()
{
return opPicture;
}



As far as I can see it should work properly but when I try to make another Image object that uses the same surface it does not work. The surface in the other image is NULL.
I'm sure that there is a stupid reason why it does not work but I can not see it at the moment and maybe you can give me some input.
Advertisement
In the copy constructor you only update the reference count but you never update the opPicture pointer.opPicture = other.opPicture;

The picture pointer don't need to be a member of Image because it is only used in one of the constructors.

In the copy constructor you only update the reference count but you never update the opPicture pointer.opPicture = other.opPicture;

The picture pointer don't need to be a member of Image because it is only used in one of the constructors.


Heh, I missed that...

After adding opPicture = other.opPicture in the copy constructor it works like a charm. Thanks!

This topic is closed to new replies.

Advertisement