tags:

views:

1020

answers:

3

I'm trying to encapsulate some functions from the C socket library into my own C++ class. I'd like to define a member function that uses the same name as its corresponding C function, but with a different signature. For example, I'd like to write the function

ssize_t MyClass::write(const void *buf);

which makes a call to

ssize_t write(int fd, const void *buf, size_t count);

When I compile I get the following errors

error: no matching function for call to ‘MyClass::write(int&, const char*&, size_t)’
note: candidates are: ssize_t MyClass::write(const char*)

I have the correct #include statements to make the call to the C socket library, but my definition of a write function seems to be shadowing it. If I change the name of my class defined function to something else, everything seems to work fine.

I'm reasonably sure that changing my function name is going to be my final solution, but could someone tell me the name of the C++ naming rule that causes this behavior? I'd like to read up on it so I know what I'm doing in the future.

+6  A: 

Have you tried calling the C function expliciting that it lives in the global namespace, like ::write?

UncleZeiv
+1  A: 

More generally, when the compiler goes looking for a function, it looks in the closest namespace first, and if it finds one with the correct name, it doesn't look any further, even if the signatures don't match.

ceo
+2  A: 

This page does a pretty good job of describing the name lookup rules in C++. Basically, once the compiler sees that write() is a class member function, it doesn't look for global functions of the same name. It then reports an error since the member function write() doesn't have the right number and types of arguments as what you gave it. The use of the unary scope resolution operator :: forces the compiler to only search the global namespace for functions named write(), which then succeeds.

Adam Rosenfield