In article <11**********************@u72g2000cwu.googlegroups .com>,
"craig" <cr**********@comcast.net> wrote:
Given two existing but different classes OldA and OldB (that can not be
made to derive from any new base class); is there a way to make them
both "observer" objects so that they can be put in one central list and
updated thru a common interface. (i.e. observer->update( ..))?
Potential solution 1 (multiple inheritence): make a small new observer
class, and two new classes: NewA: derived from OldA, and Observer,..
and NewB: derived from OldB, and Observer. When walking thru a list of
NewA's and NewB's, cast the objects as Observer. (Can this even work?)
and call it's update function.
class Observer {
public:
virtual ~Observer() { }
virtual void update() = 0;
};
class NewA : public OldA, public Observer {
public:
void update() {
// call member-functions inherited from OldA
}
};
Potential solution 2 (composition): Make a new abstract composite class
"observer" and derive concrete observers ObserverA, and ObserverB that
contain "instances" of OldA, and OldB respectively. (The problem with
this approach in my case is that OldA is QtWidget and window management
becomes cumbersome.
class NewA : public Observer {
OldA* itsOldA;
public:
NewA( OldA* oldA ): itsOldA( oldA ) { }
~NewA() { delete itsOldA; }
void update() {
// call member-functions of itsOldA
}
};
I would only use the latter if the contained object doesn't need to be
shared. IE, if you need to put a getter in the NewA class to extract
itsOldA for use, then solution 2 is problematic. However, if OldA
already has classes derived from it that also must support the Observer
interface, then you have no choice and must go with solution 2.
Potential solution 3: Any other appraoches?
Is there some ABC that OldA is derived from?
class ParentOfOldA {
public:
virtual void func() = 0;
};
class OldA : public ParentOfOldA {
public:
void func();
};
class NewA : public Observer, public ParentOfOldA {
OldA* itsOldA;
public:
NewA( OldA* oldA ): itsOldA( oldA ) { }
~NewA() { delete itsOldA; }
void update() {
// call member-functions of itsOldA
}
};
--
Magic depends on tradition and belief. It does not welcome observation,
nor does it profit by experiment. On the other hand, science is based
on experience; it is open to correction by observation and experiment.