Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ : Why cant static functions be declared as const or volatile or const volatile [duplicate]

Tags:

c++

Possible Duplicate:
C++ - Why static member function can’t be created with ‘const’ qualifier

Was curious to know the reason why static member functions cant be declared as const or volatile or const volatile ?

#include<iostream>

class Test 
{     
   static void fun() const 
   { // compiler error
       return;
   }
};
like image 909
Laavaa Avatar asked Oct 21 '12 12:10

Laavaa


People also ask

Why static methods Cannot be const?

A 'const member function' is not allowed to modify the object it is called on, but static member functions are not called on any object. It is used directly by scope resolution operator. Thus having a const static member function makes no sense, hence it is illegal.

Can static member function be declared const volatile or const volatile?

A static member function cannot be declared with the keywords virtual , const , volatile , or const volatile . A static member function can access only the names of static members, enumerators, and nested types of the class in which it is declared.

Can we declare const volatile in C?

The volatile keyword, like const, is a type qualifier. These keywords can be used by themselves, as they often are, or together in variable declarations.

Can static be const?

static const : “static const” is basically a combination of static(a storage specifier) and const(a type qualifier). Static : determines the lifetime and visibility/accessibility of the variable.


2 Answers

The cv-modifiers of the member functions correspond to the qualification of the hidden this parameter.

static functions have no this parameter. Therefore, they need no cv-qualifiers. So it was decided (IMHO rightly, as otherwise, it would have no meaning) to disallow them on static functions.

BTW static member functions can't also be virtual, pure (=0), deleted, defaulted, && etc.

like image 114
jpalecek Avatar answered Sep 27 '22 01:09

jpalecek


Because that's what the standard says:

9.4.1 Static member functions [class.static.mfct]

2) [ Note: A static member function does not have a this pointer (9.3.2). —end note ] A static member function shall not be virtual. There shall not be a static and a non-static member function with the same name and the same parameter types (13.1). A static member function shall not be declared const, volatile, or const volatile. (emphasis mine)

The reason for this is that a const (or volatile or virtual) static method wouldn't make sense (in the traditional sense, see below). For example, const implies you can't modify the object's members, but in the case of statics, there's no object to talk about.

You could argue that a const static could apply to other static members, but this option was regarded as pointless.

like image 26
Luchian Grigore Avatar answered Sep 25 '22 01:09

Luchian Grigore