Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why static void method() const is compiled error?

Tags:

c++

I have an interview, the interviewer asked me a question about const and static keyword in C++; The question is why you cannot define a member function like this:

static void func() const

He mentions somewhat *this = null causes this problem, I just did not get his idea, he didn't talk in detail.


2 Answers

The trailing const qualifier is applied to the this pointer that is passed as an implicit argument to each non-static member function. Since the function in question is static, there is no this pointer that could be qualified so the construct is bogus.

like image 108
5gon12eder Avatar answered Jun 15 '26 10:06

5gon12eder


The const keyword is used to prevent you from modifying the object that the method is called against. Static methods aren't called against an object, so it doesn't make sense to include them both.

like image 36
Mark Ransom Avatar answered Jun 15 '26 12:06

Mark Ransom