Hello folks.
I'm studing C ++ classes and trying to make a simple library.
Today when I was reading some code I found this:
OneWire::crc8
I understand the OneWire is the name of the class and crc8 is a method of the class, what I dont understand is why not they had used dot notation like "sensor.crc8(addr,7)"
This particular code is from a one-Wire library extracted from the example code on the library
Here is the part:
if (OneWire::crc8(addr, 7) != addr[7]) {
Serial.println("CRC is not valid!");
return;
At the begining of the code an object was created named ds(instance of OneWire class) soo why is the reason of using the :: between the name of the class and the method?
I couldn't tell you the official name (in Java, it's a static member function), but the idea is that the function is a member of the class, not of an instantiated object of the class.
I think it's called a static member function (same as in Java, eh?).
It is static because it does not rely on any class data (in other words a CRC can be done on any string). Since it does not belong to any instance you have to qualify it with the class name.
In c++, static means there is only one of the thing for all objects of that type, and it is shared among all instances of that class.
IIRC you can access static members through instances, in your example ds.crc8(addr, 7) as well as OneWire::crc8(addr, 7). It would be calling the same method. But understand that the result of the crc8() function does not depend on any data or state in any particular OneWire object instance like "ds".
what I dont understand is why not they had used dot notation
It is the scope resolution operator ( :: ), it can access items in namespaces, like others pointed out; static members / data in classes. It also has important uses. In a template, it can turn a non-dependant name into a dependant name ( the right hand side depends on the implementation of the left hand side, similar to 'this->' )
Also, consider this example, if you had a global var:
int foo = 5;
Alongside a function:
void test( int foo = 6 ){
foo = foo;
}
This makes no sense, however the global scope is implicitly defined, which can be explicitly specified.
void test( int foo = 6 ){
::foo = foo;
}
::foo now indicates you are using the globally defined entity, not the function parameter.
There is more to the story if you are interested, depends how deep you intend to study.