C++ Logo

std-discussion

Advanced search

Access level for defaulted comparison operators

From: Richard Hazlewood <contact.hazlewood.mail_at_[hidden]>
Date: Wed, 24 Nov 2021 15:21:16 +0000
Hi,

I was recently going through a refactoring exercise to make use of
default comparison operators.

For some hierarchical classes I was concerned about the slicing problem,
so thought no problem I'll just make the base operator protected.

However, this fails to compile (with gcc 10 & 11, -std=c++20). It
appears that the base operator is inaccessible.

Sample code:

```

#include <iostream>
#include <iomanip>

#define CE //constexpr

struct B
{
   int x = 0;

protected:
   CE bool operator==(B const&) const = default;
};

struct D : B
{
   int y = 1;

   CE bool operator==(D const&) const = default;
};


int main()
{
   D d1, d2;
   std::cout << std::boolalpha << (d1 == d2) << std::endl;
   D d3, d4; ++d4.y;
   std::cout << std::boolalpha << (d3 == d4) << std::endl;

// B b1, b2;
// (b1 == b2); // protected
}
```

Are defaulted (member) comparison operators not considered something
that is available to the hierarchy - maybe guarding against some other
nasty?

Curiously, if `constexpr` is set then gcc 11 accepts the code. However,
that won't help as soon as any more complex members are added (e.g.
`std::string`).

Received on 2021-11-24 09:21:20