Another solution that might work is the following:
Suppose that the base class is called MyBaseClass, the child classes are ChildClass1 through ChildClass5, and the function that you want to duplicate looks like this:
public int foo(Object args)
{...}
Now what you can do is create a separate class (call it "HelperFunctions" or some such) with a static method:
public static int fooHelper(BaseClass theClass, Object args)
{insert duplicated code here}
and then have the foo functions in the classes you want call that helper function.
This has a few advantages:
- You're not creating new objects or changing the type hierarchy. Since the helper function is static you can call it without needing any new objects.
- You can still call methods of the class, because you are passing in the object of type BaseClass, so you can call methods on it just like you would from within the class.
Most of the answers above talk of using a new class, but the method I am using calls many other methods of the class and also uses some of the class instance variables. If I use a mixin or compose a new class, I wont be able to implement the method.
I'm not sure I understand what the problem is. At least in my solution, you're passing in the object, so you can call whatever methods and access instance variables on the object you want. Is the problem that the instance variables or methods you want to access are private so you can't access them outside the class? In that case you can easily solve it by declaring the helper function to be a friend function (just google "c++ friend function" for tutorials on how to use them)