Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

C++, conflicting between library function and inhertited class function

#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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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);
    }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading