Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling an overloaded function from a derived class. [duplicate]

I'm trying to compile next code in Visual Studio 2010:

A {
public:
  void f(int i) {cout << i;}
};

class B: public A {
public:
  void f(string s) {cout << s;}
};

void main() {
  A a;
  B b;

  a.f(1);
  b.f("zazaza");
  b.f(1); //Compilation fail
}

But compilation fails. I cannot understand why I cannot call f(int) from parent class. What should I do to fix this problem?

like image 838
user3555886 Avatar asked May 09 '26 01:05

user3555886


1 Answers

The void f(string); in the derived class is hiding the parent's same name method, not overriding it. You can use using keyword in the derived class to un-hide it.

class B: public A
{
public:

    using A::f;
    //^^^^^^^^^

    void f(string s)
    {
        cout << s;
    }
};

Now, both two f methods are overloads to each other and the f(int) is avaiable.

like image 100
masoud Avatar answered May 11 '26 18:05

masoud