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
2010-05-24 10:42:31
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
2010-05-24 10:59:34
@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
2010-05-24 11:24:34
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
2010-05-24 11:10:52
yes, the result will be same. count can be accessed in both ways (X::count and test.count).
Donotalo
2010-05-24 11:40:34
here when i try int test.count = 10; instead of int X::count = 10; its giving an error, you know why?
oDx
2010-05-24 12:08:58
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
2010-05-25 07:20:18
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
2010-05-24 11:11:42
You don't *have to* -- `p->m` is just syntactic sugar for `(*p).m` ;)
FredOverflow
2010-05-24 11:29:49