Home > Net >  How to add a new argument to an inherited overloaded function
How to add a new argument to an inherited overloaded function

Time:07-22

I have a Class A which has a method f, and this method is overloaded.

        class A {                                                                           
    public:
    void f(int argument);
    void f(double arg1, double arg2);
    void f(char* argument1, int argument2, int argument3);
};

And then I have a class B which inherits from A. I want to add a new argument to all options of f function. Is there any other way than doing that manually? I mean, I think this will work:

    class B : public A {                                                                           
    public:
    void f(int argument, int addedArgument);
    void f(double arg1, double arg2, int addedArgument);
    void f(char* argument1, int argument2, int argument3, int addedArgument);
};

But my question is if there is some better way to do this. Thank you. :)

CodePudding user response:

The functions in B will be brand new overloads of the functions available in A.

They will hide the functions in A, so if you have a B object then you can't call the functions from A:

B b;
b.f(1, 2);  // void B::f(int argument, int addedArgument)
b.f(1);     // Error, can't find void A::f(int argument)

If you want to be able to call both the new overloads from B and the old from A you need to add the functions from A into the scope of B with the using keyword:

class B : public A {
public:
    using A::f;  // Add the A::f function overloads to B

    void f(int argument, int addedArgument);
    void f(double arg1, double arg2, int addedArgument);
    void f(char* argument1, int argument2, int argument3, int addedArgument);
};

Now you can use both sets of functions, from both A and B.

Also note that the functions in B are overloads, they do not override the functions from A.


As for if there's a "better" way to do it, then the answer is no. It's not possible to "add" arguments to functions without overloading, which means you have two definitions of basically the same function.

With that said, if the two overloads have many common parts, you could break those out into separate functions that both overloads could call.

CodePudding user response:

In simple terms, It is not possible also, If this was possible it doesn't make any sense to use the virtual method.

In your code, Instead of overriding methods, you're creating new overloading methods.

  • Related