Originally Posted by
ehnuh
Hi I would like to know if it is possible to execute a function from a derived class that inherits from a base class and trigger it on all the derived classes.
With an exception of static methods, you execute functions on objects and not classes, therefore for this to work, each instance has to be registered somewhere. If you keep such a register in the base class then I can imagine this working (I have no idea why you'd want to do that though). Here is an example:
class BaseClass {
public:
BaseClass() {
m_instances << this;
}
~BaseClass() {
m_instances.removeOne(this);
}
virtual void someMethod() {
// ...
foreach(BaseClass *instance, m_instances) {
if(instance != this) instance->someOtherMethod(); // or someMethod() but you have to make sure it is overridden correctly in each subclass or you'll get incorrect behaviour
}
// ...
}
virtual void someOtherMethod() {
}
private:
static QList<BaseClass*> m_instances; // register of instances
};
class SubClass : public BaseClass {
public:
SubClass() : BaseClass() {}
virtual void someOtherMethod() { ... }
};
class BaseClass {
public:
BaseClass() {
m_instances << this;
}
~BaseClass() {
m_instances.removeOne(this);
}
virtual void someMethod() {
// ...
foreach(BaseClass *instance, m_instances) {
if(instance != this) instance->someOtherMethod(); // or someMethod() but you have to make sure it is overridden correctly in each subclass or you'll get incorrect behaviour
}
// ...
}
virtual void someOtherMethod() {
}
private:
static QList<BaseClass*> m_instances; // register of instances
};
class SubClass : public BaseClass {
public:
SubClass() : BaseClass() {}
virtual void someOtherMethod() { ... }
};
To copy to clipboard, switch view to plain text mode
Bookmarks