Being very new to C++, I am rather confused as to when the double colon (::) qualifiers need to be used. Sometimes objects are referred to via the dotted notation (e.g. object.function() ), and at other times I see the colons being used (e.g. object::function() ). Can someone explain in very simple terms when the colons need to be used and why?
:: is the scope oprator
. is the member operator (unsure the actual name, honestly)
"::" is used when you have a class or namespace name to qualify another name. "." is used when you have an object and you want to access a member of that object.
class A
{
public:
staticvoid StaticFunction() { }
void NonStaticFunction() { }
int variable;
};
int main()
{
// if we want to call StaticFunction:
StaticFunction(); // this is an error, because 'StaticFunction' doesn't exist in the global namespace (it's not a global function)
// therefore we need to qualify it by specifying the scope. We do this with the :: operator
A::StaticFunction(); // this is OK, because now the compiler knows to look in the A class to find StaticFunction.
// in order to call non-static functions or to access variables, we need an object:
A obj; // 'obj' is our object
obj.variable = 5; // here we use the . operator because we have an object. No need for the :: operator
// because the scope is implied by the object type ('obj' is an 'A', so it knows to look in 'A' for 'variable')
obj.NonStaticFunction(); // same thing with member function calls
}