开发者

Using 'const' in class's functions [duplicate]

This question already has answers here: Meaning of 'const' last in a开发者_开发百科 function declaration of a class? (12 answers) Closed 5 years ago.

I've seen a lot of uses of the const keyword put after functions in classes, so i wanted to know what was it about. I read up smth at here: http://duramecho.com/ComputerInformation/WhyHowCppConst.html .

It says that const is used because the function "can attempt to alter any member variables in the object" . If this is true, then should it be used everywhere, because i don't want ANY of the member variables to be altered or changed in any way.

class Class2
{ void Method1() const;
  int MemberVariable1;} 

So, what is the real definition and use of const ?


A const method can be called on a const object:

class CL2
{
public:
    void const_method() const;
    void method();

private:
    int x;
};


const CL2 co;
CL2 o;

co.const_method();  // legal
co.method();        // illegal, can't call regular method on const object
o.const_method();   // legal, can call const method on a regulard object
o.method();         // legal

Furthermore, it also tells the compiler that the const method should not be changing the state of the object and will catch those problems:

void CL2::const_method() const
{
    x = 3;   // illegal, can't modify a member in a const object
}

There is an exception to the above rule by using the mutable modifier, but you should first get good at const correctness before you venture into that territory.


Others have answered the technical side of your question about const member functions, but there is a bigger picture here -- and that is the idea of const correctness.

Long story short, const correctness is about clarifying and enforcing the semantics of your code. Take a simple example. Look at this function declaration:

bool DoTheThing(char* message);

Suppose someone else wrote this function and you need to call it. Do you know what DoTheThing() does to your char buffer? Maybe it just logs the message to a file, or maybe it changes the string. You can't tell what the semantics of the call are by just looking at the function declaration. If the function doesn't modify the string, then the declaration is const incorrect.

There's practical value to making your functions const correct, too. Namely, depending on the context of the call, you might not be able to call const-incorrect functions without some trickery. For example, assume that you know that DoTheThing() doesn't modify the contents of the string passed to it, and you have this code:

void MyFunction()
{
  std::string msg = "Hello, const correctness";
  DoTheThing(msg.c_str());
}

The above code won't compile because msg.c_str() returns a const char*. In order to get this code to compile, you would have to do something like this:

void MyFunction()
{
  std::string msg = "Hello, const correctness";
  DoTheThing(msg.begin());
}

...or even worse:

void MyFunction()
{
  std::string msg = "Hello, const correctness";
  DoTheThing(const_cast<char*>(msg.c_str()));
}

neither of which, arguably, are 'better' than the original code. But because DoTheThing() was written in a const-incorrect way, you have to bend your code around it.


The meaning is that you guarantee to clients calling a const function member that the state of the object will not change. So when you say a member function is const it means that you do not change any of the objects member variables during the function call.


const, when attached to a non-static class method, tells the compiler that your function doesn't modify the internal state of the object.

This is useful in two ways:

  • If you do write code that changes internal state in your const method, the compiler catches the error, moving a programming error from run-time to compile-time.
  • If client code calls a non-const method on a constant pointer, the compiler catches the error, ensuring the "chain of not changing things" is maintained.

Typically you want to declare all non-mutating non-static class methods as const. This allows calling code to use the const qualifier on pointers, and it helps catch mistakes.

Typical C++: you can declare a class member variable "mutable" and then change it even from a const method.


The const keyword used after a method indicate that this method doesn't modify the object on which it's called. This way, this method can be called on a const version of the object.


If this is true, then should it be used everywhere, because i don't want ANY of the member variables to be altered or changed in any way?

Well, no. Sometimes you do want instance methods to modify members. For example, any set method will obviously need to set variables, so it's not the case that you should put const everywhere. But if your object's state is totally immutable, first consider whether it might not be better to have no instances at all (i.e., a static class), and if that's not the case, then make everything const.


It's quite unusual not to want to have any member variables changed, but if that's what your class requires, then you should make all your member functions const.

However, you probably do want to change at least some members:

class A {
  private: 
    int val;
  public:
    A() : val(0) {}
    void Inc() { val++; }
    int GetVal() const { return val; };
};

Now if I create two instances of A:

A a1;
const A a2;

I can say:

a1.GetVal();
a2.GetVal();

but I can only say:

a1.Inc();

trying to change the value of a constant object:

a2.Inc();

gives a compilation error.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜