tags:

views:

187

answers:

3

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

+11  A: 

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;
avakar
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!
oDx
@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.
Michael Aaron Safyan
A: 

Please check out this and this links.

Donotalo
class X{public: static int count;}test;int X::count = 10; // define static data member int main (){ int X = 0; // hides class type X cout << X::count << endl; // use static member of class X}In this example if i put the line cout << test.count << endl;instead of cout << X::count << endl;will the result be the same? that is 10.Or even this usage is correct?
oDx
yes, the result will be same. count can be accessed in both ways (X::count and test.count).
Donotalo
here when i try int test.count = 10; instead of int X::count = 10; its giving an error, you know why?
oDx
For a static member variable (here, count), you need to allocate memory explicitly (that is why int X::count = 10; appears). Because that member variable may be used without declaring object of that class type (here, X). In contrast, int test.count = 10; is not a valid way to declare a variable. So you are getting error. First of all, you need to declare X::count explicitly (like int X::count;), then you can access it either by X::count, or test.count.
Donotalo
A: 

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"

Paulo Centeno
You don't *have to* -- `p->m` is just syntactic sugar for `(*p).m` ;)
FredOverflow