16

I just wanted to know the difference between . operator and :: operator?

3 Answers 3

26

The former (dot, .) is used to access members of an object, the latter (double colon, ::) is used to access members of a namespace or a class.

Consider the following setup.

namespace ns {
    struct type
    {
        int var;
    };
}

In this case, to refer to the structure, which is a member of a namespace, you use ::. To access the variable in an object of type type, you use ..

ns::type obj;
obj.var = 1;
2
  • so, if we are using object to access something, then we have to use dot operator, and if we are using a class name then we have to use ::, right?, can you give an example also, if u dont mind!
    – defiant
    May 24, 2010 at 10:59
  • @oDx, that is correct, so if you have a static variable or function of a class, you would use "::" with the name of the class to reference them, whereas if you have a member function or member variable, you would use "." with the name of an instance of the class. May 24, 2010 at 11:24
3

Another way to think of the quad-dot '::' is the scope resolution operator. In cases where there are more than one object in scope that have the same name. You explicitly declare which one to use:

 std::min(item, item2);

or

mycustom::min(item, item2);

The dot operator '.' is to call methods and attributes of an object instance

Myobject myobject;
myobject.doWork();
myobject.count = 0;
// etc 

It was not asked, but there is another operator to use if an object instance is created dynamically with new, it is the arrow operator '->'

Myobject myobject2 = new Myobject();
myobject2->doWork();
myobject2->count = 1;
1

If you are using a pointer to an object instance, you'll have to access the members of the object using -> in place of "dot"

1
  • 2
    You don't have to -- p->m is just syntactic sugar for (*p).m ;) May 24, 2010 at 11:29

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.