Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

function names conflict in C++

Tags:

c++

conflict

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

like image 667
Wei He Avatar asked May 22 '13 07:05

Wei He


1 Answers

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 (::).

like image 168
Andy Prowl Avatar answered Oct 05 '22 09:10

Andy Prowl