简体   繁体   中英

Overloaded function in derived class (C++)

This is a very basic question, but my C++ skills are a bit rusty...

I have a base class that has a member function that takes 3 arguments, eg:

class MyBaseClass
{
public:
    int func(int a, char b, int c);
};

and a derived class that overloads that function with a 1-argument version., eg:

class MyDerivedClass : public MyBaseClass
{
public:
    int func(float a);
};

When I try to call the function from the base class on an object of the derived class, like this:

MyDerivedClass d;
d.func(1, 'a', 0);

the compiler complains that MyDerivedClass::func() does not take 3 arguments . That is true, but shouldn't I be able to access the base class function through an object of the derived class?

What am I doing wrong?

MyDerivedClass::func is hiding the name MyBaseClass::func . You can fix this with a using declaration:

class MyDerivedClass : public MyBaseClass
{
public:
    using MyBaseClass::func;
    int func(float a);
};

You probably intended to declare the method MyBaseClass::func() as virtual

But, if you really want to achieve

when I try to call the function from the base class on an object of the derived class, like this

then, you can try

MyDerivedClass d;
d.MyDerivedClass::func( 3.14f );

This compiles and works, but does not seem to be good design.

the compiler complains that MyDerivedClass::func() does not take 3 arguments

That is indeed true, per your class definition, MyDerivedClass::func() takes only one argument.

Add "using Class::func;" in MyDerivedClass.

class MyDerivedClass : public MyBaseClass
    {
    public:
        using MyBaseClass::func;
        int func(float a);
    };

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM