Fausto01
Fausto01

Reputation: 211

C++ inheritance and same funciton names

I have this situation:

class A
{
  public:
    A();
    virtual ~A();
    void doSomething();
};


class B : public A
{
  public:
    B();
    void doSomething(int parameter);
};

If I do the following:

int main()
{
  B b;
  b.doSomething();
}

It gives me a compile error (no matching function). How can I solve that without changing the B funcion name? B derives from A so it has also the doSomething() function without parameters. Why is it not working? Thanks for the help.

Upvotes: 2

Views: 107

Answers (2)

jfMR
jfMR

Reputation: 24738

This answer is just an alternative to this solution in case you aren't allowed to modify class B.


If you aren't allowed to modify class B for adding using A::doSomething; inside the class (as already suggested here), you can take a pointer to the member function A::doSomething(), then call it through that member function pointer on the instance b:

auto fptr = &A::doSomething;
B b;
(b.*fptr)();

or simpler, by properly qualifying the member function no member function pointer is needed:

B b;
b.A::doSomething(); // calls A::doSomething()

Upvotes: 1

Jarod42
Jarod42

Reputation: 217235

Currently, B::doSomething hides A::doSomething.

You might use using to resolve your issue:

class B : public A
{
  public:
    using A::doSomething;
    B();
    void doSomething(int parameter);
};

Upvotes: 3

Related Questions