'Why can a const function not be called on a const object in this case? [closed]

Hey I'm trying to look at the basics of OOP and I do not understand why in this particular instance, I cannot call a member function which is defined const on an object which is also const. But since both are deemed const, I dont change behavior for any of the objects or their attributes right? What does this mean? VS code says that the object has type qualifiers that are incompatible with the member function g. Any information will be appreciated. Thank you!

class D
{
    private:
        double x;
        
    public:
        D()
        {
            x = 2.0;
        }
        const double &g() {
            return x;
        }
    
};

int main()
{
    const D d;
    d.g();
}   


Solution 1:[1]

You placed the const in the wrong place. D::g is not a const-member function. It is a non-const member function (that returns a const reference). You want:

    const double& g() const {
                    //^^ const member function
    //^---------^ return type
        return x;
    }

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1