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?
I don't see any reason why you can't do this. Take this example:
Now initialize a QPointer like this:
You can then call methods on the 'abstract' class as you would normally with a QPointer
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.
I hope that helps.
Extra note: You should also check pointer.isNull() to make sure that the QPointer actually contains something.