returning *this gives Weffc++ warning

837 views Asked by At

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?

1

There are 1 answers

0
PilouPili On BEST ANSWER

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).