const static member functions

R

Rahul Joshi

Hi,

Is it possible to define static member functions that are 'const',
i.e. they just read but do not modify the static data members of
a class? Declaring functions like:

class SomeClass {
static int read() const;
};

gives compiler errors, so it seems this is not directly supported.
Is there any other way in which I can get this effect?

Thanks,
Rahul
 
V

Victor Bazarov

Rahul Joshi said:
Is it possible to define static member functions that are 'const',
i.e. they just read but do not modify the static data members of
a class? Declaring functions like:

class SomeClass {
static int read() const;
};

gives compiler errors, so it seems this is not directly supported.

Correct. There is no object associated with the function (classes
are not objects in C++), so nothing to make obtain the const-ness
from.
Is there any other way in which I can get this effect?

What effect? Constant member functions are chosen in overload
resolution over non-constant ones when called with a constant
object (and vice versa). How would the compiler use the 'const'
with a function that doesn't have an object associated with it?

If you know that you're implementing a function that is supposed
not to change the static data, just don't change them.

Victor
 
S

Shane Beasley

Rahul Joshi said:
Is it possible to define static member functions that are 'const',
i.e. they just read but do not modify the static data members of
a class?

Not really, no.
Declaring functions like:

class SomeClass {
static int read() const;
};

gives compiler errors, so it seems this is not directly supported.
Is there any other way in which I can get this effect?

You could implement the Singleton design pattern (i.e., a single,
static instance of class SomeClass) and make read() a const,
non-static member function which operates on the instance. Or,
depending on your intentions, you could make the relevant static data
members const.

That's about it, really.

- Shane
 

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

No members online now.

Forum statistics

Threads
474,263
Messages
2,571,064
Members
48,769
Latest member
Clifft

Latest Threads

Top