-2

I need help understanding C++ syntax. I am referencing Derek Molloy Github,

/Chp08/i2c/cpp/I2CDevice.cpp

In his implementation file, he has this section in his code

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;
}

I am confused on this particular line, if((this->file=::open(name.c_str(), O_RDWR)) < 0). What exactly does =::open mean? I know the fstream library in C++ has an open method, but why include the ::?

uBoscuBo
  • 81
  • 8

2 Answers2

3

name::func() means to calling func under the namespace name. Some functions like open are defined in the global namespace which has no name, so ::open calls a function named open from the global namespace. It is used here to avoid calling I2CDevice::open and to explicitly call the operating system's open function.

paolo
  • 2,345
  • 1
  • 3
  • 17
0

When doing a function call you can prefix the function with the namespace it is in:

<NameSpaceDecl>::<Function>(<Param>);

This usually looks like this:

std::sort(begin, end);

But things in the global namespace, can be accessed by the shorter ::

::open(<Stuff>);

So this is a way of specifying a specific function when the compiler may have picked a function from a local scope instead.

In your case you probably need to use ::open() as your class has function I2CDevice::open() and the compiler would have tried to use that one (and generated an error). But by being specific with ::open() you are saying use the version of open() that is in the global namespace.

Martin York
  • 257,169
  • 86
  • 333
  • 562