1

Given this code:

struct base
{
    base() = default;
    virtual ~base() = default;
    base(const base&) = default;
    base(base&&) = default;
    base& operator=(const base&) = default;
    base& operator=(base&&) = default;

    virtual void debug(){ std::cout << "base debug\n"; }
};

struct derived : public base
{
public:
    void debug() override { std::cout << "derived debug\n"; }
    void derived_only() { std::cout << "derived only\n"; }
};

derived g_d; // NOLINT
void get_base(base &b)
{
    b = g_d; // clang tidy complains about this, so, fair enough
}

This gives the following clang tidy warning:

clang tidy warning

But then if I assigned to a base reference first (pointers / refs are allowed to point to derived):

void get_base(base &b)
{
    base &b_temp = g_d;
    b = b_temp;
}

Then the clang-tidy warning goes away.

But my question is, is this really any different to the initial code - i.e. its just masking the issue, or is this a legitimate "work-around".

Ideally I would just pass pointers/references only and not take copies. But in this case it would be convenient to use this workaround.

The warning does actually say that the overridden function debug() is discarded - which is exactly what we want - we only want/need the base class members.

code_fodder
  • 15,263
  • 17
  • 90
  • 167
  • Does using static_cast help ? – Ahmed AEK Aug 23 '23 at 07:06
  • @AhmedAEK no, that gives the same clangtidy issue - and as far as I can tell, just does the same slicing – code_fodder Aug 23 '23 at 07:10
  • Slicing is generally unexpected, so the warning. if it is done on purpose, see how to disable the warning locally. Your workaround might be detected in future version if not explicitly marked as official workaround... – Jarod42 Aug 23 '23 at 07:21
  • @Jarod42 I can silence that clangtidy warning no problem, but the question is, is the second implementation any different to the first? - I think your comment suggests that it is (except for the extra assignment)? – code_fodder Aug 23 '23 at 07:32
  • 1
    They behave identically (You might even check assembly [Demo](https://godbolt.org/z/bT91ec1KG) (same assembly)). (There are no extra assignment, there is initialization of an alias/reference) – Jarod42 Aug 23 '23 at 07:51
  • @Jarod42, ah ok, thanks - so this really is just the same as the questions telling clangtidy to be quiet :) thanks – code_fodder Aug 23 '23 at 07:55

0 Answers0