Abstract Class Assignment Operator Overload

An instance of an abstract class can only exist as a subobject for a derived type. A public copy assignment operator would allow for incorrect partial assignments to occur. The copy assignment operator should be protected, or alternatively defined if copying is to be prohibited in this class hierarchy.

#include <cstdint> class A { public: virtual ~A () = 0; A& operator = (A const &) &; // @@- Non-Compliant -@@ }; class AA : public A { }; void foo() { AA obj1; AA obj2; A* ptr1 = &obj1; A* ptr2 = &obj2; *ptr1 = *ptr2; // partial assignment } class B { public: virtual ~B () = 0; protected: B& operator = (B const &) &; // @@+ Compliant +@@ }; class C { public: virtual ~C () = 0; protected: C& operator = (C const &) & = default; // @@+ Compliant +@@ }; class D { public: virtual ~D () = 0; D& operator = (D const &) & = delete; // @@+ Compliant +@@ };


  • HIC++ v3.3 – 3.3.14

Click here for references

I just encountered with question on parashift.com regarding Abstract base classes in c++ .

Author has provided the solution in which pure virtual member function has been created in Abstract Base Class.The purpose of this function is to create and return the address of clone object of ABC pointing to. Here I am bit confused that what is the use of creating this virtual function and overriding the Assignment operator and copy constructor if we achieve the same thing without doing this.

Then we implement this method in each derived class. Here is the code for derived class Circle:

Now suppose that each Fred object “has-a” Shape object. Naturally the Fred object doesn’t know whether the Shape is Circle or a Square or … Fred’s copy constructor and assignment operator will invoke Shape’s method to copy the object:

As I think we can achieve above behavior without overriding the Assignment operator or copy constructor. If we have two object (P_ pointing to Circle) and (P_ pointing to Square) of type Fred. then

In the default case ,(Address of Square) of will get copied to to . now will point to Square. Only thing we need to take care is to delete the object of Circle otherwise it will be dangling state.

Why has the author mentioned the above technique to solve this problem? Please Advise.


0 Replies to “Abstract Class Assignment Operator Overload”

Lascia un Commento

L'indirizzo email non verrà pubblicato. I campi obbligatori sono contrassegnati *