Skip to content

tutorial6: when and why do I have to add *parent as a class parameter and when not? #5

@dsyleixa

Description

@dsyleixa

hi,
as tp tutorial6:
when do I have to add *parent as a class parameter and when not?

e.g., not:
.cpp


Bullet::Bullet(): QObject(), QGraphicsRectItem(){
    setRect(0,0,10,50);
    QTimer * timer = new QTimer(this);
    connect(timer,SIGNAL(timeout()),this,SLOT(move()));
    timer->start(50);
}

header:

class Bullet: public QObject, public QGraphicsRectItem{
    Q_OBJECT
public:
    Bullet(QGraphicsItem * parent=0);  // parent only in header
public slots:
    void move();
};

but e.g., yes:
.cpp


Enemy::Enemy(QGraphicsItem *parent): QObject(), QGraphicsRectItem(parent){ // <<<<<<<<<<<<<<<<<<<<<<<<<<<
    int random_number = rand() % 700;
    setPos(random_number,0);
    setRect(0,0,100,100);
    QTimer * timer = new QTimer(this);
    connect(timer,SIGNAL(timeout()),this,SLOT(move()));
    timer->start(50);
}

header:

class Enemy: public QObject, public QGraphicsRectItem{
    Q_OBJECT
public:
    Enemy(QGraphicsItem * parent=0);  // parent in header like above
public slots:
    void move();
};

i.e., why can't I just declare
Enemy::Enemy(): QObject(), QGraphicsRectItem(){ ...}[/code]`
similar to the Bullet file?

(ref.: https://github.com/MeLikeyCode/QtGameTutorial/tree/master/tutorial6)

(edit,
BTW, in previous tutorials https://github.com/MeLikeyCode/QtGameTutorial/tree/master/tutorial1 ... https://github.com/MeLikeyCode/QtGameTutorial/tree/master/tutorial5 this "parents" thing has not been added at all for either class)

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions