what are the colons for?

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?

Many thanks,

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

For example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
class A
{
public:
  static void 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
}
Last edited on
when the colons need to be used and why?

It works within class methods as requested.
An operator becomes a stranger to its very roots.
A label is a type without it. Probably that's why.



Topic archived. No new replies allowed.