C ++ overload with virtual = statement

here is the code for my question:

class ICommon { public: virtual ICommon& operator=(const ICommon & p)const=0; }; class CSpecial : public ICommon { public: CSpecial& operator=(const CSpecial & cs)const { //custom operations return *this; } }; CSpecial obj; 

Basically: I want the ICommon interface to force its descendants to implement operator = operator, but did not want to have any tricks in the implementation. The compiler says: β€œIt is not possible to create an abstract class. Any help / advice would be appreciated.

+4
source share
4 answers

To repeat what Naven said, operator=() defined in CSpecial is incompatible with that defined in ICommon and leads to overloading rather than overriding. Although you can have covariant return types (as you did), the arguments themselves cannot be covariant.

Also, you defined ICommon::operator=() as const, which seems inconsistent. In a derived class, you made it non-constant (as expected), but again, this makes the function signatures more incompatible.

The idea of ​​Naveen clone() is probably your best bet. Otherwise, you can pass the ICommon const link to your CSpecial operator=() and try some dynamic_cast<>() magic inside, but it smells funny.

Good luck

+2
source

This is because the function signature in CSpecial is different from the pure virtual function you defined in the abstract base class. You can use the virtual copy constructor to copy. Basically, you define the pure virtual function ICommon* clone() = 0 in the base class and implement it in each derived class. When this function is called, a copy of the object on which it is called is created.

+3
source

You can use a recursive template to achieve the desired result:

 template<typename T> struct IAssignable { virtual T& operator =(const T&) = 0; }; struct Impl : IAssignable<Impl> { virtual Impl& operator =(const Impl&) { return *this; } }; 

This is not used and cannot be used to force the copy constructor to execute. So I'm not sure if this is terribly useful, and you will probably be better off with the proposed clone() option. But this is a useful design in general.

+1
source

Basically: I need an interface To make its descendants implement = the operator, but they don’t want to have any tricks in the implementation. The compiler says msgstr "it is not possible to instantiate an abstract class. Any help / advice would be appreciated.

Consider dividing the open interface of the base class into an implementation (virtual):

 class ICommon { public: ICommon& operator=(const ICommon & p) { if(this == &p) return *this; copy(p); return *this; } protected: virtual void copy(const ICommon& p) = 0; }; class CSpecial : public ICommon { protected: virtual void copy(const ICommon& p) { // TODO: copy values from p } }; 
0
source

Source: https://habr.com/ru/post/1310191/


All Articles