Question

In the comments of a recent question I posted (C++: Bad Form to Call Base Class Asssignment Operator in Derived Class Constructor?) I ran into another issue with regards to how I use static_cast to go from a derived type to a base type. Supporting documenation for the issue can be found here: Why does static_cast(*this) to a base class create a temporary copy?.

My main problem is that I'm now having no issue using static_cast to cast this to the base class inside my derived class. However, I cannot perform a static cast from a derived reference to a base reference. I only do this in my equality operator of the derived class. Here's the issue:

bool Derived::operator==(const Derived& other_derived) {
  // first call the operator == from the base class...
  if (static_cast<Base&>(*this) == static_cast<Base&>(other_derived)) {
    // continue checks for derived member variables
  }
}

The compiler yells at the if statement above. It has no problem with the static_cast of this, but cannot interpret the static_cast from the derived class to the base class. If I remove the reference, this compiles fine, but as shown in the two referenced questions, this will unnecessarily create a temporary object.

As a result, I'm wondering if perhaps I'm missing a constructor to go from a derived class to a base class. Where would I write such a constructor (since it is a constructor for the base type)? I don't think that it would make sense to do so within the base's source code since doesn't that essentially make the base class custom and ruin the spirit of reusable code?

An easier alternative would be to just accept the temporary creation of the object within this function, but the function may end up freqeuently called, and therefore I'm not sure if I can accept the performance hit.

Is there anything else that I'm missing of that I should consider? As always, thanks in advance for the help.

Was it helpful?

Solution

All credit goes to @jogojapan for this. The operator== in both the derived and base classes were never defined/declared as const. Changing all the equality and inequality operators to const functions yielded the program compiling. Also I had to slightly change the static_cast synatax to cast to a const type. That is:

static_case<const Base&>(derived_object);

Thanks again for the help!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top