I have the following class hierarchy:
class Base { // This class cannot be modified public: Base(int a, int b, int c) { if ( a == 100 && b == 200 && c < 100 ) // whatever condition throw "Error!"; } }; class Derived : public Base { // this class can be modified public: Derived(int a, int b, int c) : Base(a, b, c) {} };
The Derived class is used in many places in the code, so it cannot be replaced with any factory function.
Now the question is, is there any construction that would allow me to correct the values of a, b, c before calling the Base constructor?
I know that I can use functions such as:
Derived(int a, int b, int c) : Base(FixA(a), FixB(b), FixC(c)) {} int FixA(int a) { return a; } int FixB(int b) { return b; } int FixC(int c) { return c; }
but it will not allow me to set the correct values in the case when the values of bc depend as in the above c-tor example of the base class.
I thought to expand this to:
Derived(int a, int b, int c) : Base(FixA(a,b,c), FixB(a,b,c), FixC(a,b,c)) {} int FixA(int a, int& b, int& c) { return a; } int FixB(int& a, int b, int& c) { return b; } int FixC(int& a, int& b, int c) { return c; }
I suppose there should also be some kind of flag indicating that the correction has already been completed. I am not sure if this is really correct with C ++.
I know that the best solution is actually throwing an exception.