Let's say I have an abstract class Parent
and classes Child1
and Child2
that both inherit from it.
Now I need to properly implement an assignment operator between Child1
and Child2
.
The problem that immediately arises is that I cannot define an operator of form
Child1 operator=(const Child2 & rhs);
because this requires the class Child2
to be completely defined at the point of the operators definition and the same for the operator defined in Child 2
.
I tried defining the operator as
Child1 operator=(const Parent & rhs);
And that seemed to work in most of the cases, but failed in case of the following:
vector<Parent *> children;
children.push_back(new Child1());
children.push_back(new Child2());
(*children[1]) = *const_cast<const Parent *>(children[0]);
In this case compiler wanted to run the assignment operator
Parent operator=(const Parent &)
which I cannot implement because the compiler won't let me define a return type which is an abstract class.
So how do you do this properly?
This is a job for separate header and implementation files and forward declarations (pseudo code follows):