0

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;
};
ChemiCalChems
  • 612
  • 12
  • 31
kstn
  • 537
  • 4
  • 14
  • 1
    The two functions **are** in the same scope. They have different **access specifiers**, but that doesn't affect overload resolution. The protected version is the better match. Full stop. Same thing if it was private. – Pete Becker Mar 06 '23 at 19:07

2 Answers2

3

Visibility of a function doesn't alter overload resolution rules. There is no error here, double& GetValue() is simply a better candidate than const double& GetValue() const

The Dreams Wind
  • 8,416
  • 2
  • 19
  • 49
1

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

Paul Sanders
  • 24,133
  • 4
  • 26
  • 48