There are two classes in a library I use, lets call them class A
and class B
to keep things generic. Class B
inherits from class A
, so something like:
class A{
...
}
class B: public A{
...
}
So nothing fancy, but I can't edit either of these classes directly. Now I wanted to add some functionality to class A, so I subclass it as, say, myClassA
, and add the functionality in the subclass. This works great when I use myClassA
, but of course anywhere I use classB
still inherits from the original class A
, and not myClassA
.
How can I make a subclass of class B
that inherits from myClassA
instead of the original classA
? Would it work to simply have the subclass inherit from BOTH class B
and myClassA
, even though class B
already inherits from the original class A
?
EDIT: I just tried the "Inherit from BOTH" option and can confirm it does not work, at least not without a lot more work. Probably the diamond issue mentioned in the comments. So unless there is a way to override class B
's inheritance of class A
with myClassA
, I may have to simply re-implement the changes I made to my subclass of class A
in a subclass of class B
, although that would be a violation of the DRY principle...
EDIT 2: To make this a little more concrete, take for example the standard "shape" class example. So in this case you'll have a base class of, say, rectangle
, and rectangle
is in tern inherited by a class of square
. Now I want to add functionality, say a "move" function that shifts the position of the object by a specified amount. This would be the same for both rectangle
and square
, so ideally I'd implement it in the rectangle
class, and square
would inherit it. However, since I don't have access to the rectangle
or square
classes directly, I can only work with subclasses. Thus my desire to make a square
subclass that inherits from my rectangle
subclass rather than the base rectangle
class.
EDIT 3: To restate and clarify the question in terms of the more concrete example, "Can I/How can I create a subclass of square
but have it inherit from my_rectange
(a rectangle
subclass) INSTEAD OF inheriting from rectangle
?" Or, to put it another way, "Can I/How can I replace a base class with something of my own if I can't modify the class directly?"