-1
class mca1
{
    public:
        void power(float m,int n)
        {
           cout<<"RESULT OF "<<m<<"^"<<n<<"="<<pow(m,n);
        }
};
class mca2:public mca1
{
    public:
        void power(int m,int n)
        {
            cout<<"\nRESULT OF "<<m<<"^"<<n<<"="<<pow(m,n);
        }
};

please tell me is there any way to call overridden functions without use of virtual function....just on the basis of arguments?

AABHINAAV
  • 23
  • 4

1 Answers1

0

You can pull the base class function into the derived class scope, making them behave as overloaded functions.

class mca1
{
    public:
        void power(float m,int n)
        {
           cout<<"RESULT OF "<<m<<"^"<<n<<"="<<pow(m,n);
        }
};
class mca2:public mca1
{
    public:
        using mca1::power;
        void power(int m,int n)
        {
            cout<<"\nRESULT OF "<<m<<"^"<<n<<"="<<pow(m,n);
        }
};
super
  • 12,335
  • 2
  • 19
  • 29
  • it is giving error "call of overloaded power(double,int) is ambigous – AABHINAAV Apr 18 '20 at 08:06
  • If you try to call it with a double, it will do that since both conversions are valid. If you call it with a float or int it will do the right thing. `mca2 m; m.power(2.0, 1);` will fail but `m.power(2.9f, 1);` and `m.power(2, 1);` will work. – super Apr 18 '20 at 08:12
  • You can add one more overload for double if you need both to work. Maybe even just forward to the float version. That's just how function overloading in `c++` works. – super Apr 18 '20 at 08:15
  • is there any specific reason that double works without any problem but float type give an error? – AABHINAAV Apr 18 '20 at 08:28
  • I'm guessing you mean when using literals to call the function? `2.0` is of type double, not float. If you want a float you need to write `2.0f`. Again, it's just the rules of the language. `1` is and `int`, not `char` or `long long`. `"text"` is `cont char*` and not `std::string` etc. – super Apr 18 '20 at 08:32
  • Another thing that comes into play here is that if you use `float` and call the function with a double, both the conversion to `int` and `float` are narrowing conversions. So none of them is a better match -> ambigous. If you use `double` and call the function with a float, only the conversion to `int` is narrowing, but not the conversion to double, so the double function is a better match -> not ambiguous. – super Apr 18 '20 at 08:36
  • I got it now...thank you so much – AABHINAAV Apr 18 '20 at 08:36