Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ - Why static member function can't be created with 'const' qualifier

Today I got a problem. I am in the need of a static member function, const is not a must but a better. But, I didn't succeed in my efforts. Can anybody say why or how?

like image 576
prabhakaran Avatar asked Aug 12 '11 03:08

prabhakaran


People also ask

Can static member functions be const?

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.

What does the const member function qualifier do?

The const qualifier at the end of a member function declaration indicates that the function can be called on objects which are themselves const. const member functions promise not to change the state of any non-mutable data members.

What are the restrictions on the use of static member functions?

You cannot have static and nonstatic member functions with the same names and the same number and type of arguments. Like static data members, you may access a static member function f() of a class A without using an object of class A .

What limitations does a static member function have?

What limitation does a static member function have? Static member functions can only access member variables that are also static.


1 Answers

When you apply the const qualifier to a nonstatic member function, it affects the this pointer. For a const-qualified member function of class C, the this pointer is of type C const*, whereas for a member function that is not const-qualified, the this pointer is of type C*.

A static member function does not have a this pointer (such a function is not called on a particular instance of a class), so const qualification of a static member function doesn't make any sense.

like image 179
James McNellis Avatar answered Sep 28 '22 04:09

James McNellis