Due to this question and the answers, it's not 100% clear whether attributes are inherited or not, but probably they're not since it's not stated in the standard. That's why if we have only the declaration marked as nodiscard
in the base class, and compile using Clang, we only get a warning if we access the object using a "base" pointer.
The problem with the following code is that it does not warn at all when compiling with GCC (versions 8.1 through 11.1). Having nodiscard
only in the Child1
, in both classes, or only in Base
, calling through a Base
pointer or a Child1
pointer, all these do not help.
#include <memory>
class Base {
public:
[[nodiscard]]
virtual int getIdentifier() const = 0;
};
class Child1 : public Base {
public:
[[nodiscard]]
int getIdentifier() const override {
return 1;
}
};
int main()
{
std::unique_ptr<const Child1> p1 { new Child1 };
p1->getIdentifier();
std::unique_ptr<const Base> p2 { new Child1 };
p2->getIdentifier();
}
Is this a sort of a bug in GCC (not likely since every single version available in Compiler Explorer, from 8.1 to 11.1, produce the same result), or am I doing something wrong?