0

According to CppCoreGuidelines C.60 and C.63, copy assignment operator (e.g Foo& operator=(const Foo& x)) and move assignement operator (e.g Foo& operator=(const Foo&& x)) should be declared non-virtual.

Can you explain me the reason of this recommandation ? As suggested by this answer, I imagine that this is to avoid leaks of memory but I don't see exactly how the use of virtual will induce it.

  • You're in luck. Remy's been online recently and might still be around to explain. Otherwise, does [virtual assignment operator C++](https://stackoverflow.com/questions/669818/virtual-assignment-operator-c) help fill in the blanks? – user4581301 Dec 07 '21 at 22:11
  • Side note: Usually when people are asking about this they are often [looking for cloning](https://isocpp.org/wiki/faq/virtual-functions#virtual-ctors). – user4581301 Dec 07 '21 at 22:16
  • @user4581301 if you feel like it's a duplicate, I can delete it or flag it as duplicate. Nevertheless, after reading [here](https://stackoverflow.blog/2010/11/16/dr-strangedupe-or-how-i-learned-to-stop-worrying-and-love-duplication/) that "What we want is on the order of 4 or 5 similar-but-not-quite-the-same duplicates to cover all possible search terms and common permutations of the question", I hesitate. –  Dec 07 '21 at 23:19
  • 1
    No worries. If I'd thought it was a perfect duplicate, I would have already closed the question. Brian's answer below targets this precisely, and a precise and concise answer beats an answer where you have to read between the lines a bit every time. – user4581301 Dec 07 '21 at 23:57

1 Answers1

7

There is no reason why a copy or move assignment operator should be virtual. Making it virtual possibly incurs costs associated with having virtual functions (e.g. the requirement to allocate a vptr within each object of the class) for no benefit.

Let's say you have a class Base, which has a virtual copy assignment operator:

virtual Base& operator=(const Base&);

What will happen when you write a derived class, class Derived : public Base? It will have its own copy assignment operator:

Derived& operator=(const Derived&);  // possibly also virtual

If you don't declare such an operator, the compiler will implicitly declare one with this signature (modulo some details that are not relevant here).

Because the derived class's copy assignment operator has a different argument type from that of the base class, there is no overriding relationship between them. And there's no point in writing a virtual function if it's never going to be overridden.

Brian Bi
  • 111,498
  • 10
  • 176
  • 312