PDA

View Full Version : Base class and Derived classes (inheritance question)



ehnuh
23rd October 2012, 08:56
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.

For example I have a base class with a generic template widget (for user interface), it has several functionality that can be called by the derived classes.

Then I have a class that inherits this user interface.

If for example I call the protected function of the baseclass through the instance of the derived class, is there a way that I can trigger it for all derived classes that inherit the function of the base class?

wysota
23rd October 2012, 10:16
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() { ... }
};

Ashkan_s
23rd October 2012, 10:46
I think in Qt there's a possibility of doing this using singal and slots. Emitting a signal when the base class function is called, where the signal -in all instances of the derived class- is connected to a slot which calls the base class function. The signal can carry a variable which informs the slot that it should not emit the signal again to prevent a loop.