QPointer for abstract base class

2.3k views Asked by At

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?

1

There are 1 answers

3
Liz On BEST ANSWER

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.