C++ Programmer Question:

Explain me are you allowed to have a static const member function?

Tweet Share WhatsApp

Answer:

A const member function is one which isn’t allowed to modify the members of the object for which it is called. A static member function is one which can’t be called for a specific object.

Thus, the const modifier for a static member function is meaningless, because there is no object associated with the call.

A more detailed explanation of this reason comes from the C programming language. In C, there were no classes and member functions, so all functions were global. A member function call is translated to a global function call. Consider a member function like this:

void foo(int i);
A call like this:

obj.foo(10);
…is translated to this:

foo(&obj, 10);
This means that the member function foo has a hidden first argument of type T*:

void foo(T* const this, int i);
If a member function is const, this is of type const T* const this:

void foo(const T* const this, int i);
Static member functions don’t have such a hidden argument, so there is no this pointer to be const or not.

Download C++ Programmer PDF Read All 59 C++ Programmer Questions
Previous QuestionNext Question
Explain me which operator can be used in C++ to allocate dynamic memory?Please explain what is difference between shallow copy and deep copy? Which is default?