What is the best way to draw a rectangle on the screen?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
///------------CLASS RECTANGLE-------------///
class Rectangle: public Shape{
protected:
int x, y;
int w, h;
public:
void drawRectangle(SDL_Renderer*);
};
void Rectangle drawRectangle(SDL_Renderer* renderer){
SDL_Rect r;
r.x=x;
r.y=y;
r.w=w;
r.h=h;
SDL_RenderFillRect(renderer, &r);
}
///----------------------------------------///
It feels odd to make a new object of SDL_Rect every time I call this. Should I make it a private variable? Is there a function that just takes x, y, w, and h so this all could be avoided?
Since x, y, w and h store the exact same information as a SDL_Rect you could remove x, y, w and h and instead let the Rectangle class contain a single data member of type SDL_Rect.
1 2 3 4 5 6 7 8 9 10
class Rectangle : public Shape {
protected:
SDL_Rect r;
public:
void drawRectangle(SDL_Renderer*);
};
void Rectangle::drawRectangle(SDL_Renderer* renderer) {
SDL_RenderFillRect(renderer, &r);
}
Another alternative is to let Rectangle inherit from SDL_Rect. This allows you use x, y, w and h as regular members as before, and you still don't need to create a new object to pass to SDL_RenderFillRect because you can pass the Rectangle object itself.
1 2 3 4 5 6 7 8
class Rectangle : public Shape, protected SDL_Rect {
public:
void drawRectangle(SDL_Renderer*);
};
void Rectangle::drawRectangle(SDL_Renderer* renderer) {
SDL_RenderFillRect(renderer, this);
}