Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

whats the difference between dot operator and scope resolution operator

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

like image 445
defiant Avatar asked May 24 '10 10:05

defiant


2 Answers

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;
like image 61
avakar Avatar answered Oct 02 '22 15:10

avakar


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;
like image 42
mrflash818 Avatar answered Oct 02 '22 14:10

mrflash818