Can static member functions be const?

M

mimi

Hi,all.
The section 13.5.1 of the <C++ primer 3rd edition> says, a static
member frunction may not be declared as const or volatile. I could not
explain to myself why? The constness seems to be irrelevant to whether
the function is static or non-static.
Furthermore, i am not sure the following program is correct. According
to the book, it should be wrong, but my compiler says it is right.

class Account
{
public:
static const double interest() {return _interestRate;}
private:
static double _interestRate; //I know i should declared it as
const, but it is also OK.
};

double Account::_interestRate = 1;

int main()
{
Account::interest();
return 0;
}
 
I

Ian Collins

mimi said:
Hi,all.
The section 13.5.1 of the <C++ primer 3rd edition> says, a static
member frunction may not be declared as const or volatile. I could not
explain to myself why? The constness seems to be irrelevant to whether
the function is static or non-static.

The constness of a member function relates to the instance of the class
it is called on ('this'). A const member function can not change the
state of the class instance. A static member function is not called on
an instance of a class, so it can't be const.
Furthermore, i am not sure the following program is correct. According
to the book, it should be wrong, but my compiler says it is right.

class Account
{
public:
static const double interest() {return _interestRate;}

The *function* isn't const here, the *return* type is.
 
M

mimi

The constness of a member function relates to the instance of the class
it is called on ('this'). A const member function can not change the
state of the class instance. A static member function is not called on
an instance of a class, so it can't be const. Wonderful reply. Thank you.



The *function* isn't const here, the *return* type is.
Oh,yes. To make the function const, i should declared it as static
interest() const;
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,961
Messages
2,570,131
Members
46,689
Latest member
liammiller

Latest Threads

Top