If the default copy-assignment operator of class
B
is not deleted, [class.copy]/28The implicitly-defined copy/move assignment operator for a non-union class
X
performs memberwise copy-/move assignment of its subobjects. The direct base classes ofX
are assigned first, in the order of their declaration in the base-specifier-list [i.e. in the order in which they're listed afterclass X : /*here*/ {/*...*/};
], and then the immediate non-static data members ofX
are assigned, in the order in which they were declared in the class definition.Similarly, [class.copy]/15
The implicitly-defined copy/move constructor for a non-union class X performs a memberwise copy/move of its bases and members.
The order is: first the base class(es) (base class subobjects), then the direct non-static data members, similarly to 1).
For the behaviour described in 1) and 2), no. Virtual assignment operators are hardly ever useful. Constructors may not be virtual at all (doesn't make sense).
In order for a virtual function in a derived class
B
to override a virtual function in a base classA
, it must have the same parameter types. That is, you could have avirtual A& operator=(A const&);
in the base classA
, but the override in classB
had to look likevirtual B& operator=(A const&);
, which is not a copy-assignment operator forB
, because of the parameter type.Not without "hacks". And you're not actually overloading it, but hiding all base class assignment operators. Otherwise, this would be legal:
class A {}; class B { int i; }; A a; B b = a; // using A::operator=(A const&)
Subclassing, assignment operator and copy constructor
-
28-06-2022 - |
Question
I have a bunch of questions related to this, I couldn't find exact answers. Class A is the main class, and B is a subclass
If A::operator=(const A & other) was defined, does the default implementation of B::operator= copies members of B then calls A::operator= ?
If A copy constructor was defined, does the default implementation of the copy constructor for B copy-constructs members of B, then calls A copy constructor?
Do I need to define above functions virtual in A to get this behavior? (I suppose yes for operator= and no for the copy constructor, as virtual constructors is a nonsense?)
Can I forbid overloading the assignment operator or the copy constructor for subclasses of A, to force the use of default implementations?
The idea behind this, being to offer a plugin API for my users. I need the API to be C++ as scripts are too slow (I'll try JIT compilation one day), but it should be very simple.
Solution