1
I2CDevice::I2CDevice(unsigned int bus, unsigned int device) {
    this->file=-1;
    this->bus = bus;
    this->device = device;
    this->open();
}

int I2CDevice::open(){
   string name;
   if(this->bus==0) name = BBB_I2C_0;
   else name = BBB_I2C_1;

   if((this->file=::open(name.c_str(), O_RDWR)) < 0){
      perror("I2C: failed to open the bus\n");
      return 1;
   }

   if(ioctl(this->file, I2C_SLAVE, this->device) < 0){
      perror("I2C: Failed to connect to the device\n");
      return 1;
   }

   return 0;
}

The above is part of a code doing Linux I2C interface, my question is in the line:

this->file=::open(name.c_str(), O_RDWR)

I think this is trying to assign a value to the file descriptor this->file using open() function. But why there is a "::" symbol? Why not just "open()".

user253751
  • 57,427
  • 7
  • 48
  • 90
user31415926
  • 33
  • 1
  • 5

1 Answers1

5

That is C++ name resolution. The :: operator separates namespaces. When it starts a name, it is an explicit reference to the top level, global namespace. Its use here guarantees that it is referring to the open function declared by the C library and not any open that happens to be in the class, the current namespace, or any using namespace declarations.

In this specific example, ::open is required because it is inside an open class function. Simply calling open here would cause a name resolution error because there's an open in the class but no matching override. If the arguments did match, it would be a recursive call which isn't what you want.

Zan Lynx
  • 53,022
  • 10
  • 79
  • 131