Cruz
30th May 2010, 16:44
Hello!
Admittedly, I'm not the most experienced C++ programmer and this is the first time I'm trying to use inheritance and virtual functions. It doesn't work like it should and I can't figure out why. Here is the juice.
class PathPiece
{
public:
virtual void pos()
{
qDebug() << "Called base";
}
void draw(QPainter* painter)
{
pos();
}
};
class LinePiece : public PathPiece
{
public:
void pos()
{
qDebug() << "Called line";
}
};
LinePiece is a kinf of PathPiece and it's supposed to override the pos() function, while the draw() function remains central in PathPiece. If I do
LinePiece lp;
lp.draw(painter);
Then everything works. However, if I do
QList<PathPiece> list;
list << LinePiece();
list[0].draw();
then it doesn't. The pos() function of the base class is called. Isn't virtual supposed to be for cases exactly like this?
Admittedly, I'm not the most experienced C++ programmer and this is the first time I'm trying to use inheritance and virtual functions. It doesn't work like it should and I can't figure out why. Here is the juice.
class PathPiece
{
public:
virtual void pos()
{
qDebug() << "Called base";
}
void draw(QPainter* painter)
{
pos();
}
};
class LinePiece : public PathPiece
{
public:
void pos()
{
qDebug() << "Called line";
}
};
LinePiece is a kinf of PathPiece and it's supposed to override the pos() function, while the draw() function remains central in PathPiece. If I do
LinePiece lp;
lp.draw(painter);
Then everything works. However, if I do
QList<PathPiece> list;
list << LinePiece();
list[0].draw();
then it doesn't. The pos() function of the base class is called. Isn't virtual supposed to be for cases exactly like this?