Search code examples
c++overloading

Visibility of function overloads with different scope


The code below gives error: error: ‘double& Sample::GetValue()’ is protected within this context | double v = ms.GetValue();. If the protected function if deleted it compiles fine. Is it the bug of the compiler that cannot select the correct function overload with different scope?

class Sample
{
public:
    Sample() {}
    virtual ~Sample() {}
    const double& GetValue() const {return v;}
    void Print() {std::cout << v << std::endl;}
protected:
    double& GetValue() {return v;}
private:
    double v;
};

class Sample2
{
public:
    Sample2() {}

    void Compute()
    {
        double v = ms.GetValue();
    }

private:
    Sample ms;
};

Solution

  • What The Dreams Wind said, but the compiler doesn't know you want to call const double& GetValue() const (which should be double GetValue() const, btw) because ms is not declared const.

    There's an easy fix though:

    void Compute()
    {
        const Sample &const_ms = ms;
        double v = const_ms.GetValue();
    }
    

    Live demo