Question

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 Child2to 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?

Was it helpful?

Solution

This is a job for separate header and implementation files and forward declarations (pseudo code follows):

// parent.h
class Parent {};

// child1.h
class Child2; // forward declaration
class Child1 : public Parent
{
   Child1& operator=(cosnt Child2& rhs);
};

// child2.h
class Child1; // forward declaration
class Child2 : public Parent
{
   Child2& operator=(cosnt Child1& rhs);
};

// child1.cpp
#include "child1.h"
#include "child2.h"

Child1& Child1::operator=(cosnt Child2& rhs)
{
  // ...
};

// child2.cpp
#include "child2.h"
#include "child1.h"

Child2& Child2::operator=(cosnt Child1& rhs)
{
  // ...
};
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top