0

I have this two classes: board.h and scene.h.When I run program like this everything works fine: scene.cpp

scene::scene()
{
  basescene=new QGraphicsScene;
  additem();

}

void scene::additem()
{
    board *_board=new board;
    QPixmap boarditem (":/images/board.png");
    _board->setPixmap(boarditem);
    basescene->addItem(_board);
}

scene.h

class scene:public QGraphicsScene
{
public:
    scene();
    QGraphicsScene *basescene;
    void additem();
};

board.h

class board:public QGraphicsPixmapItem
{
public:
    board();
};

board.cpp

board::board()
{

}  

But when i run it like this:

scene.h

class scene:public QGraphicsScene
{
public:
    scene();
    QGraphicsScene *basescene;

};

scene.cpp

scene::scene()
{
  basescene=new QGraphicsScene;
  board _board;

}

board.h

class board:public QGraphicsPixmapItem,public scene
{
public:
    board();
    void additem();
    board *_board;
};

board.cpp

board::board()
{
   additem();
}

void board::additem()
{
board *_board=new board;
QPixmap boarditem (":/images/board.png");
_board->setPixmap(boarditem);
basescene->addItem(_board);
}

The program crashes and debugger says that the error is in scene class and the code has a segment fault.I googling and it said that is some pointer issue... I'm newbie in c++ and debug thing and sorry about my bad english.

behrooz
  • 7
  • 3
  • There is a mess in your code. You can completely remove the code working well, but put full code which fails. For example, where is the constructor of `chessscene` ? – Ezee Aug 28 '14 at 06:36
  • I edit the post that's not the problem... I realy tired..didn't see that issue in post so sorry about that. – behrooz Aug 28 '14 at 07:30

1 Answers1

1

You inherited class board from scene.
When you create an instance of board the scene constructor is executed, then the board constructor is executed. But in the scene constructor you create a new instance of board. And scene constructor of this new instance creates another instance of board. And so on till infinity.

If you need more info about constuctors calling:
Order of calling constructors/destructors in inheritance

EDIT: Actually if it has overcome this issue and walk further it would come to the board constructor which calls addItem which creates another board instance. In the constructor of this new instance addItem will be called again and it will try to create another one board and again, and again.

So you have a couple of recursive constructor calls.

Community
  • 1
  • 1
Ezee
  • 4,214
  • 1
  • 14
  • 29