I read so many answers saying static const functions can't exist. Eg. this Q&A. and this Q&A
What if this is the use case:
#include<iostream>
using namespace std;
class Sample{
static const int privx;
static int privy;
public:
static int getPrivx(){
return privx;
}
static int getPrivy(){
// privy += 100;// I want to avoid changes in static variables through a static function => I need const static function
return privy;
}
};
const int Sample::privx = 90;
int Sample::privy = 100;
int main(){
cout<<Sample::getPrivx()<<endl;
cout<<Sample::getPrivy()<<endl;
}
So, use case: There are a lot of static variables declared in class. During development phase, I want to prevent developer from manipulating values of these static variables via operations inside a (static) function. Basically, compiler must shoot error saying changing value in static variable not allowed. The exact reason why const methods are used for i.e. no manipulations inside it (to calling object members of course).
What are your solutions? I think a static & const function must be allowed as:
static int getPrivy() const{}
P.S. I asked this question before without considering const functions syntax => hence readers may find unrelated answers. Apologies.
This code is illegal, it's const qualified static method
class Sample{
public:
static int fun() const {
return 0;
}
};
This code is OK, it's a const qualified non-static method
class Sample{
public:
int fun() const {
return 0;
}
};
This code is OK, it's a static method with a const return type
class Sample{
public:
static const int fun() {
return 0;
}
};
I guess the problem is that you don't realise what it means that a method is const
. It has nothing to do with the return type, it's about the type of the this
pointer within the method (as the quote says).