PDA

View Full Version : inheritence and virtual



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?

Zlatomir
30th May 2010, 16:56
You need to use pointers to achieve that, something like this:
QList<PathPiece*> list; you are truncating your values if you don't.

So: Base obj = Derived objD; //isn't valid it performs a cast and you will have a Base object
You need Base* obj = Derived *objD; // and this is ok, virtual mechanism works with this

Cruz
30th May 2010, 17:07
Thank you for the clarification!

Zlatomir
30th May 2010, 17:14
Your welcome, careful the last two line isn't c++ code, i said it in c++ style, just to make an example.

And for your Base class write a destructor and declare it virtual (so the objects get destroyed properly no mater what object the Base pointer points to)