1

I am writing an expression-parsing library. It is written with Qt, and I have a class structure like this:
QCExpressionNode-Abstract Base Class for all pieces of an expression
QCConstantNode-Constants in an expression (extends QCExpressionNode)
QCVariableNode-Variables in an expression (extends QCExpressionNode)
QCBinaryOperatorNode-Binary Addition, Subtraction, Multiplication, Division and Power operators (extends QCExpressionNode)

I would like to be able to use smart pointers (like QPointer or QSharedPointer), but I am running into the following challenges:
-Can a QPointer be used with abstract classes? If so, please provide examples.
-How to cast a QPointer to a concrete subclass?

demonplus
  • 5,613
  • 12
  • 49
  • 68
Nathan Moos
  • 3,563
  • 2
  • 22
  • 27

1 Answers1

3

I don't see any reason why you can't do this. Take this example:

class Parent : public QObject
{
public:
   virtual void AbstractMethod() = 0;
};

class Child: public Parent
{
public:
   virtual void AbstractMethod() {  }

   QString PrintMessage() { return "This is really the Child Class"; }
};

Now initialize a QPointer like this:

QPointer<Parent> pointer = new Child();

You can then call methods on the 'abstract' class as you would normally with a QPointer

pointer->AbstractMethod();

Ideally this would be enough, because you could just access everything you need with the abstract methods defined in your parent class.

However, if you really need to differentiate between your child classes or use something that only exists in the child class, you can use dynamic_cast.

Child *_ChildInstance = dynamic_cast<Child *>(pointer.data());

// If _ChildInstance is NULL then pointer does not contain a Child
// but something else that inherits from Parent
if (_ChildInstance != NULL)
{
   // Call stuff in your child class
   _ChildInstance->PrintMessage();
}

I hope that helps.

Extra note: You should also check pointer.isNull() to make sure that the QPointer actually contains something.

Liz
  • 8,780
  • 2
  • 36
  • 40
  • Could I use `qobject_cast`? And, could I use a typedef, such as `QCExpressionNode_ptr` as a `QPointer`? – Nathan Moos Apr 14 '11 at 02:04
  • 1
    @Nathan Moos documentation for qobject_cast says "The qobject_cast() function behaves similarly to the standard C++ dynamic_cast()", so I assume that should work yes. And I did try to add typedef QPointer Parentptr; and use it instead of declaring it each time, and it worked. So yes you can do that too. – Liz Apr 14 '11 at 15:56
  • Thanks! That answers my question completely. – Nathan Moos Apr 16 '11 at 00:00