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

  1. If A::operator=(const A & other) was defined, does the default implementation of B::operator= copies members of B then calls A::operator= ?

  2. 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?

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

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

Was it helpful?

Solution

  1. If the default copy-assignment operator of class B is not deleted, [class.copy]/28

    The implicitly-defined copy/move assignment operator for a non-union class X performs memberwise copy-/move assignment of its subobjects. The direct base classes of X are assigned first, in the order of their declaration in the base-specifier-list [i.e. in the order in which they're listed after class X : /*here*/ {/*...*/};], and then the immediate non-static data members of X are assigned, in the order in which they were declared in the class definition.

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

  3. 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 class A, it must have the same parameter types. That is, you could have a virtual A& operator=(A const&); in the base class A, but the override in class B had to look like virtual B& operator=(A const&);, which is not a copy-assignment operator for B, because of the parameter type.

  4. 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&)
    
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top