Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Member function hidden in derived class

Tags:

c++

Please look at the following code:

#include <iostream>
using namespace std;

class A {
  public:
    A() {};    
    virtual void foo(double d) { cout << d << endl; }
    virtual void foo(double d, int a) = 0;
  };

class B : public A {
  public: 
    B() {};
    virtual void foo(double d, int a) { cout << d << endl << a << endl; }  
  };

int main()
  {
  B b;
  b.foo(3.14);
  return 0;
  }

The compiler (tried g++ and visual c++ 2008) says that there's no function like B:foo(double). The exact message of g++ is:

main.cpp:21: error: no matching function for call to ‘B::foo(double)’

It looks like the effect of hiding rule, but in my opinion the rule should not be used here, since I'm not overriding foo(double) and both foo methods are defined in base class.

I know that I can fix the problem with

using A::foo;

declaration in the derived class B.

Can you explain why the code does not compile and what rules of C++ apply here?

like image 707
Wacek Avatar asked Jul 05 '10 07:07

Wacek


People also ask

Can member functions be private?

Private: The class members declared as private can be accessed only by the functions inside the class. They are not allowed to be accessed directly by any object or function outside the class. Only the member functions or the friend functions are allowed to access the private data members of a class.

Can member function in derived class have the same name as that of one in the base class?

In C++, function overloading is possible i.e., two or more functions from the same class can have the same name but different parameters. However, if a derived class redefines the base class member method then all the base class methods with the same name become hidden in the derived class.

What is function hiding C++?

This process is referred to as name hiding. In a member function definition, the declaration of a local name hides the declaration of a member of the class with the same name. The declaration of a member in a derived class hides the declaration of a member of a base class of the same name.

Can derived class access public members of base class?

You can derive classes using any of the three access specifiers: In a public base class, public and protected members of the base class remain public and protected members of the derived class. In a protected base class, public and protected members of the base class are protected members of the derived class.


1 Answers

The hiding rule is not about overriding, it is about hiding of names. If the derived class declares a member function, this hides other base class member functions with the same name. This also happens in your case.

like image 123
sth Avatar answered Oct 16 '22 00:10

sth