What can a 'const' method change?

后端 未结 5 631
遇见更好的自我
遇见更好的自我 2020-12-05 23:46

C++ methods allow a const qualifier to indicate that the object is not changed by the method. But what does that mean? Eg. if the instance variables are pointer

5条回答
  •  忘掉有多难
    2020-12-05 23:50

    const basically prevents changing the class instance members' values inside the function. This is useful for more clearer interface, but pose restrictions when using inheritance for example. It's sometimes a little bit deceiving (or a lot actually), as in the example you posted.

    const would be most appropriate for Get functions, where it is obvious that the caller is reading a value and has no intentions of changing the object state. In this case you would want to limit the inherited implementations as well to adhere to constness, to avoid confusion and hidden bugs when using polymorphism.

    For example

    class A{
         int i;
       public:
         virtual int GetI() {return i;};
    }
    
    class B : public A{
       public:
         int GetI() { i = i*2; return i;}; // undesirable
    }
    

    changing A to:

    virtual int GetI() const {return i;};
    

    solves the problem.

提交回复
热议问题