Can't access child method from parent?
-
Good day, wondering if anyone has a clue what is happening here. I went through a C++ and QT tutorial and this should work I'm thinking. For some reason I can't see the ChildB getValues() method in the qDebug() << parent-> call in the runThis() method. Shouldn't that parameter QSharedPointer<Parent> parent have access to the child methods? I do get the getNames() method to show no issues
void FunctionClass::runThis(QSharedPointer<Parent> parent) { qDebug() << parent->???; // can only see the getNames() method, not the getValues() } class Parent : public QObject { Parent(QObject *parent = nullptr); virtual QString getNames() = 0; } class ChildA : public Parent { QString getNames() override; } class ChildB : public Parent { QString getNames() override; int getValues(); }
-
Good day, wondering if anyone has a clue what is happening here. I went through a C++ and QT tutorial and this should work I'm thinking. For some reason I can't see the ChildB getValues() method in the qDebug() << parent-> call in the runThis() method. Shouldn't that parameter QSharedPointer<Parent> parent have access to the child methods? I do get the getNames() method to show no issues
void FunctionClass::runThis(QSharedPointer<Parent> parent) { qDebug() << parent->???; // can only see the getNames() method, not the getValues() } class Parent : public QObject { Parent(QObject *parent = nullptr); virtual QString getNames() = 0; } class ChildA : public Parent { QString getNames() override; } class ChildB : public Parent { QString getNames() override; int getValues(); }
@Calicoder
Hi,parent knows nothing about ChildB.
If parent is an instance of ChildB, you can do:ChildB* b=qobject_cast<ChildB*>(parent); if(b) qDebug()<<b.getValues();
[EDIT] or dynamic_cast (i see no Q_OBJECT declaration)
-
@Calicoder
Hi,parent knows nothing about ChildB.
If parent is an instance of ChildB, you can do:ChildB* b=qobject_cast<ChildB*>(parent); if(b) qDebug()<<b.getValues();
[EDIT] or dynamic_cast (i see no Q_OBJECT declaration)
-
@mpergand Genius, need to read up on that qobject_cast code. This worked, thank you so much!
@Calicoder You also need to understand why you need to cast (you can also use dynamic_cast).
Parent has no getValues() method, so you need to cast the pointer to ChildB to be able to call this method. And of course you need to check the pointer after casting as parent is not going to always be ChildB instance.