Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ / Qt Coding style - where should a #define go

I am trying to build a break-out game clone in Qt. I need to figure out what type of a QGraphicsItem my ball collided with. For example if I the ball collides with the wall, the ball just bounces off, if it collides with a brick it has to bounce off and destroys the brick. To find out what kind of QGraphicsItem it is, I figured the best way to do that is probably to override QGraphicsItem::type() (Please let me know if this is not the right way!).

In the following code for brick.h I set my 'Brick' to have a Type of 3. Now, the value 3 looks really cumbersome to track. I would instead prefer to declare something with a '#define'

#include <QGraphicsItem>

//should this #define be here?
//#define BRICK_SPRITE 3

class Brick : public QGraphicsItem
{
public:
    Brick(const QPixmap& p, QGraphicsScene *scene = 0);
    virtual QRectF boundingRect() const;
    virtual void paint( QPainter *painter,
                        const QStyleOptionGraphicsItem *option,
                        QWidget *widget );

    QPainterPath shape() const;

    enum { Type = 3 }; //enum {Type = BRICK_SPRITE}

    int type() const { return Type; }

private:
    QPixmap pixmap;
};

Where is a good location to place the statement '#define BRICK_SPRITE 3' ? I have several other files in the project. Should I place all the definitions in a separate header file?

like image 859
Mathai Avatar asked Dec 28 '22 00:12

Mathai


1 Answers

Why not just use Type instead of 3? enums in c++ are implicitly convertible to int

If you really wanted a new name instead, I suggest you use a const int variable instead of a #define -- it is type and namespace safe, while preprocessor macros aren't.

Something like:

class Brick : public QGraphicsItem
{
  static const int BRICK_SPRITE = 3;
  // rest of the class definition
};

According to the documentations I could find, the approach you are taking with the enum and overriding type() is indeed the preferred way

like image 54
Attila Avatar answered Jan 08 '23 19:01

Attila