I am currently having an issue with using a function defined as a const in the base class.
I am implementing a derived class using the above virtual function but with a non const return value. I would like to implement this without changing the base class as there are other outside classes that use this virtual function. The reason for not changing this virtual function is that there exists other derived classes that use the same function.
Any help greatly appreciated.
For example:
I am working on a implementing a derived class function double DerivedClass1::Function() with varying return values which is a virtual function defined in double BaseClass::Function() const. This same function is used by double DerivedClass2::function() const and double DerivedClass3::Function() const for which I have no control over. How do I do this without any or minimal changes to the base class.
You have:
You want:
So, first thing you need to add a non-const virtual function to
Base, otherwise you’re not overriding anything. The question is, what should the base class function be defined as? For minimal disruption it should do the same thing that calling the function via a non-const reference currently does — call the const function:I think this could still potentially break existing code, for example if you took pointers to the const and non-const versions of the function, then previously they would compare equal and now they don’t:
For typical users of the
Baseclass, adding the new function is probably harmless.However, you say: “using the above virtual function but with a non const return value”, and your example function already has a non-const return value (
double) even with the const version of the function. So answers can’t address this, and it’s possible that by concealing your real use-case, you’re getting worse answers than you would with an example that better reflects your actual code.