tonni
tonni

Reputation: 1255

Why use scope operator (::) before class initialization in C++?

I sometimes see before initialization class scope operator ::, why is it used there?

What is differences between for example:

HRESULT hRes = ::CoInitializeEx(NULL, COINIT_APARTMENTTHREADED);

and

HRESULT hRes = CoInitializeEx(NULL, COINIT_APARTMENTTHREADED);

Upvotes: 0

Views: 148

Answers (2)

MSalters
MSalters

Reputation: 179779

:: refers to the global namespace. You'd find names there anyway, so it's not often required.

However, there are 2 reasons why you'd use this. An unqualified name can potentially come from many namespaces, and there are non-trivial rules (such as Argument-dependent lookup) to determine which namespaces to search in which order. A qualified name is looked up only in the namespace given.

The second reason is that inside class member functions, unqualified names are first looked up in class scope, and again a qualified name avoids this.

Upvotes: 6

Shivaraj Bhat
Shivaraj Bhat

Reputation: 847

It simply means as below:

HRESULT hRes = ::CoInitializeEx(NULL, COINIT_APARTMENTTHREADED);
The "CoInitializeEx" function uses the global scope // Not from local scope.

and

HRESULT hRes = CoInitializeEx(NULL, COINIT_APARTMENTTHREADED);
The "CoInitializeEx" function uses the local Scope. 

Upvotes: 3

Related Questions