2

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, e.g.:

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

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

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?

Jeff Loughlin
  • 4,134
  • 2
  • 30
  • 47
  • 2
    See this thread? http://stackoverflow.com/questions/1896830/why-should-i-use-the-using-keyword-to-access-my-base-class-method – taocp Apr 01 '14 at 19:46

3 Answers3

6

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);
};
juanchopanza
  • 223,364
  • 34
  • 402
  • 480
  • I knew it had to be something simple. It's been a long time since I've dusted off my C++ hat. I never saw the `using` keyword before - is that new? – Jeff Loughlin Apr 01 '14 at 20:06
  • @JeffLoughlin `using` has been around since the beginning. It can do more stuff in C++11, but the use shown above is old-school. – juanchopanza Apr 01 '14 at 20:09
  • I was a C->C++ convert about 12 years ago, then back again about 3 years later, so I guess I just never had an occasion to learn about `using` during my brief C++ experience. Thanks for the explanation. – Jeff Loughlin Apr 01 '14 at 20:19
1

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.

Arun
  • 19,750
  • 10
  • 51
  • 60
0

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

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