Why overloaded new operator is implicitly static and how we are able to allocate memory by calling overloaded new operator without scope resolution operator?
In my view if something is static then we can call it in main by through class name.
class xyz
{
void* operator new (size_t size); //implicitly declared static
void operator delete (void *p); //implicitly declared static
};
int main()
{
C *p = new C;
delete p;
}
The main reason why the (::) cannot be overloaded is that only operators that take in values as parameters can be overloaded. The scope resolution operator does not take a value as parameter.
Answer: Scope resolution operator (::) cannot be overloaded in C language.
Scope resolution operator in C++ can be used for: Accessing a global variable when there is a local variable with same name. Defining a function outside a class. Accessing a class's static variables.
The draft C++ standard says in section 5.3.4
New paragraph 9 that if the new expression does not begin with ::
then it is looked up in the scope of they type first and then if not found globally:
If the new-expression begins with a unary :: operator, the allocation function’s name is looked up in the global scope. Otherwise, if the allocated type is a class type T or array thereof, the allocation function’s name is looked up in the scope of T. If this lookup fails to find the name, or if the allocated type is not a class type, the allocation function’s name is looked up in the global scope
As to why it is implicitly static, it seems like it would be inconvenient restriction to require an instance of the type in order to invoke the member allocation function. It seems like would also require different syntax since how would the compiler know which instance to use which would make things messy.
The fact that member allocation functions are implicitly static is covered in section 12.5
Free store:
Any allocation function for a class T is a static member (even if not explicitly declared static).
All the operators are implicit. You don't have to use the scope operator for all the other operators either.
Think of how annoying it would be:
int a = 4 int::operator* 6;
And this is exactly the reason they made it this way.
And besides that, all the operators are parsed in the lexical processing of the code. The meaning of those literals can be user defined:
Section 2.14.8 discusses the literal rules:
A user-defined-literal is treated as a call to a literal operator or literal operator template (13.5.8). To determine the form of this call for a given user-defined-literal L with ud-suffix X, the literal-operator-id whose literal suffix identifier is X is looked up in the context of L using the rules for unqualified name lookup (3.4.1). Let S be the set of declarations found by this lookup. S shall not be empty.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With