c++compilation

How can a C++ compiler detect a non-const function body?


Having stumbled over the following piece of code:

class Person
{
private:
    char name[10];
public:
    // this won't compile:
    char* getName_1() const {
        return name;
    }
    // this will: 
    const char* getName_2() const {
        return name;
    }
};

I am wondering exactly how a compiler can tell that getName_1() is not a const function. Because there is no piece of code inside the function body that is actually modifying a member variable.


Solution

  • Since getName_1 is marked as const all fields of this class are treated as const.

    So type of name in getName_1 is const char[10].

    This can't be converted implicitly to char * (return type), so compiler reports an error.