0

Suppose the following case (Dreaded Diamond):

EXAMPLE

   class Base //It's the Base class
{
    //...
    Base& operator=(const Base&); //Copy construct
    //...
};

class Derived1:virtual public Base
{
    //...
    Derived1& operator=(const Derived1&);
    //...
}

class Derived2:virtual public Base
{
    //...
    Derived2& operator=(const Derived2&);
    //...
}

class Derived12:public Derived1, public Derived2
{
    //...
    Derived12& operator=(const Derived12&);
    //...
}

Example:

//...
Base* object1 = new Derived12; 
Base* object2 = new Derived12;

*object1 = *object2;  //this line
//...

PROBLEM

When "this line" is performed, the "operator=" function, from Base, is called.

Yet the result I seek is not this. I would like the assignment operator applied to be the one specified in Derived12 class. I understand that overloading "operator=" function is impossible, because the signature of each function would differ from class to class.


QUESTION

  1. Is there any way to make the compiler understand what is the assignment function I want to be applied ?
  2. If it's not possible with operator overloading, can you suggest some other way?

Thank you, in advance, for any suggestion.


UPDATE:

First, about the Suggested Question Similar To Mine. It does not answer my question. There I understood that in case I have an assignment of derived class object to base class object, the operator= in base class may just fill it's "untouched", during assignment, members with some default values.

Here I asked whether it's possible to make the compiler see -- that's the derived class I'm referring to and not the base. I would like to, somehow, make the assignment work with derived class members and not with the base ones.

I think I should explain the purpose of my question.

I have a similar problem I want to solve. Speaking in terms of the example above: I want to create an array of pointers to objects of mixed types: Derived, Derived1, Derived12 (each time a new object is created, the program checks if it's already present in array: if yes - new object isn't added, if no - the new object is assigned to the next uninitialized object in array.) I thought that using an array of pointers to base class would be the solution, but then encountered this problem. May be it's not the best method.

Community
  • 1
  • 1
wonderingdev
  • 1,132
  • 15
  • 28
  • 2
    Possible duplicate of [virtual assignment operator C++](http://stackoverflow.com/questions/669818/virtual-assignment-operator-c) – cadaniluk Nov 29 '15 at 15:09
  • Comments are not for extended discussion; this conversation has been [moved to chat](http://chat.stackoverflow.com/rooms/96527/discussion-on-question-by-john-g-assignment-operator-and-class-inheritance). – Martijn Pieters Nov 30 '15 at 08:12

0 Answers0