code_fodder
code_fodder

Reputation: 16341

returning *this gives Weffc++ warning

I have some code here that I am compiling with -Weffc++ -Wall -Wextra.

Basically I have this snippet:

class base
{};

class test : public base
{
public:
    base& operator=(int)
    {
        return *this;
    }
};

and I get the warning: warning: 'operator=' should return a reference to '*this' [-Weffc++]. I am not really sure what to make of that warning. I have read that this is perfectly ok (i.e. to return a deferenced this).

Is there a way I can keep my complier happy?

Upvotes: 1

Views: 896

Answers (1)

PilouPili
PilouPili

Reputation: 2699

Change your code to:

class test : public base
{
public:
     test& operator=(int)
     {
        return *this;
     }
};

And everybody will be happy, not just your compiler.

PS: If you wish to know more the warnings produced by -Weffc++ are an extract of the recommendations found in this book :

Effective C++: 55 Specific Ways to Improve Your Programs and Designs, Addison–Wesley, 1992, (ISBN 0-321-33487-6).

Upvotes: 6

Related Questions