Whats the point of const?
I've noticed that you can put constants within a class, and then change them as if they were normal values by const flagged member functions. I want to know, what do you expert programmers out there actually use constants for? Whats the advantage. I would really just like to hear a scenario where a constant would be better, because I can't think of one. Sorry, it's just driving me nuts :D
Re: Whats the point of const?
Quote:
Originally posted by Grins2Pain
I've noticed that you can put constants within a class, and then change them as if they were normal values by const flagged member functions.
Uhh, either I'm misunderstanding you, or I think you are wrong. I don't see how constants within a class can be modified by const flagged member functions. Maybe you can give a small example.
Here's my example of when const is better:
Code:
// SocketServer.h
...
class SocketServer
{
public:
SocketServer(int listenPort);
...
int GetListenPort() const { return LISTEN_PORT; }
...
private:
const int LISTEN_PORT;
...
};
...
// SocketServer.cpp
...
SocketServer::SocketServer(int listenPort) : LISTEN_PORT(listenPort)
{
...
}
...
I made LISTEN_PORT const because in my scenario above it should never change for any instance of the socket server. Since it is const, I will never accidentally set it to something else in the code. I would have to specifically remove the const specification to do so, as would any other person working on this code.
I made GetListenPort() const because it does not affect the state of the object and so if somebody has a const SocketServer object they will be able to call that method. Why would somebody ever have a const SocketServer object? Maybe they have a const reference to it so they can log info like the Port number. Maybe they did that for efficiency reasons, since I believe compilers can optimize in certain situations when they know an object won't be modified.
Anyway, that is my example.