Same function with const and without - When and why?

后端 未结 7 1745
终归单人心
终归单人心 2020-12-01 11:44
T& f() { // some code ... }
const T& f() const { // some code ... }

I\'ve seen this a couple of times now (in the introductory book I\'ve b

相关标签:
7条回答
  • 2020-12-01 12:42

    But why would you have both functions in one and the same class definition?

    Sometimes you want to provide different semantics for same operation depending on whether it's being invoked on const object OR non-const object. Let's take an example of std::string class:-

    char& operator[](int index);
    const char& operator[](int index) const;
    

    In this case when operator[] invoked through const object you won't let user to change the content of the string.

    const std::string str("Hello");
    str[1] = 'A';     // You don't want this for const.
    

    On the other hand,In case of non-const string you let user to change the content of string. That's why a different overload.

    And how does the compiler distinguish between these?

    Compiler checks whether that method is invoked on const object OR non-const object and then appropriately call that method.

    const std::string str("Hello");
    cout << str[1];           // Invokes `const` version.
    
    std::string str("Hello");
    cout << str[1];           // Invokes non-const version.
    
    0 讨论(0)
提交回复
热议问题