0
#include <iostream>
#include <unistd.h>
using namespace std;
class A{
    public:
        bool close(){ return true; }
};
class B: public A{
    public:
        void fun(){
            (void) close(1);
        }
};
int main() {
    B b;
    b.fun();
    return 0;
}

In class B I want to call the function close(1) which is in library unistd.h. FYI: close(int fileDes) used to close the file descriptors in process.

So how to overcome the issue. I got the below error:

source.cpp: In member function 'void B::fun()':
source.cpp:11:27: error: no matching function for call to 'B::close(int)'
   11 |             (void) close(1);
      |                           ^
source.cpp:6:14: note: candidate: 'bool A::close()'
    6 |         bool close(){ return true; }
      |              ^~~~~
source.cpp:6:14: note:   candidate expects 0 arguments, 1 provided

So how to overcome the issue, so that It will call the function in unistd.h file.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
R_S
  • 11
  • 3
  • Use `::close(1)`? – Sam Varshavchik Sep 09 '22 at 12:15
  • See dupe: [c++ member function hides global function](https://stackoverflow.com/a/73590850/12002570). The solution is also given in the linked dupe. In particular, use the scope resolution `operator::` like `::close(1)` – Jason Sep 09 '22 at 12:19
  • Also, any [good c++ book](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) explains how lookup works. – Jason Sep 09 '22 at 12:22

1 Answers1

0

In the scope of the member function fun the name close as an unqualified name is searched in the scope of the class

    void fun(){
        (void) close(1);
    }

And indeed there is another member function close in the base class with such a name.

So the compiler selects this function.

If you want to use a function from a namespace then use a qualified name as for example

    void fun(){
        (void) ::close(1);
    }
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335