Wei He
Wei He

Reputation: 107

function names conflict in C++

Class B inherits from Class A. Class A have a virtual function named bind.

Class A {
  virtual void bind();
}

class B: public A {
  B();
}

In the constructor of B, it uses bind (int __fd, __CONST_SOCKADDR_ARG __addr, socklen_t __len) function from <sys/socket.h>.

#include <sys/socket.h>

B::B () {
  int sockfd = socket(AF_INET, SOCK_STREAM, 0);
  sockaddr_in server_addr, client_addr;
  if(sockfd < 0)
    perror("ERROR opening socket.\n");
  bzero((char*)&server_addr, sizeof(server_addr));
  server_addr.sin_family = AF_INET;
  server_addr.sin_addr.s_addr = INADDR_ANY;
  server_addr.sin_port = 2333;
  if(bind(sockfd, (struct sockaddr *)&server_addr, sizeof(server_addr)) < 0)
    perror("ERROR on binding.\n");
  listen(sockfd, 1);
}

Compilers throws errors saying that the two bind functions conflict. I know that I can create a wrapper for bind in sys/socket.h. Is there any elegant and easier ways to resolve the conflict?

Thanks

Upvotes: 6

Views: 2609

Answers (1)

Andy Prowl
Andy Prowl

Reputation: 126412

Just qualify the call:

if (::bind(sockfd, (struct sockaddr *)&server_addr, sizeof(server_addr)) < 0)
//  ^^

This will tell the compiler to look for a function called bind in the global namespace - I am assuming that bind() does live in the global namespace; if it does not, then you should specify the name of the namespace where it lives before the scope resolution operator (::).

Upvotes: 18

Related Questions