Caligari
Caligari

Reputation: 1421

C++ Inheritance - changing a parent to a grandparent

I have an issue in a C++ project that I am doing some work on. I apologise in advance for my lack of C++ OOP knowledge.

I have a series of classes that all inheret from a common parent, eg:

class child : public parent
{
     public:
        ...
};

My issue is that I need to modify one function in parent to suit my code; unfortunately (while I have access to the source) the parent class is shared by other projects, and my intended change would cause side-effects that would break other people's code. I can make some changes if the project mainter approves, however - and he usually does if there are no side-effects (eg scope).

While obviously I could just copy that original parent, modifying it and effectively branching the code, I really don't want to do that for maintainability purposes.

So my question - is it possible to have the original parent class act as a grandparent, and create a simple one-function parent class that overrides the grandparent function, and change my code to inherit from the new parent - all other calls not implemented in the new parent being passed to the grandparent? And if so, how would I do this (in broad terms)? Or is there a better solution? Or am I just way off track altogether?

I hope that's clear. Thanks for any help, I'm groping in the dark a bit with C++.

Upvotes: 1

Views: 330

Answers (2)

R Sahu
R Sahu

Reputation: 206577

If you think the functionality is going to be useful for only one child, add the code to that child only.

If you think the functionality is going to be useful for more children, add the code to that parent class but give it a new name. Existing other child classes wouldn't be impacted by this. You can migrate the existing children to use the new functionality as and when you are allowed to do so.

Alternately, create an API function, not a class member function, that the child class can use for the time being. Again, existing child classes and their usages wouldn't be impacted by this change. If other child classes need to take advantage of that functionality, you can migrate them one at a time. Whether the API function can be promoted as a member function can be left as a future decision.

Upvotes: 1

kvanbere
kvanbere

Reputation: 3352

You could have the other person change their class so that the specified method is virtual: https://en.wikipedia.org/wiki/Virtual_inheritance

Then you could override it in either the child, or make a new common parent.

Upvotes: 1

Related Questions