I have 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) {}
};
class Derived is used in many places in code, so it cannot be replaced with some kind of factory function.
now the question is if there is some construct that would allow me to fix a,b,c values before calling Base constructor?
I know I can use functions like:
Derived(int a, int b, int c) : Base(FixA(a), FixB(b), FixC(c)) {}
int FixA(int a) { /*fix a value*/ return a; }
int FixB(int b) { /*fix b value*/ return b; }
int FixC(int c) { /*fix c value*/ return c; }
but it wont allow me to set correct values in case when a b c values are dependent like in above Base class c-tor example.
I was thinking of extending 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) { /*fix a b c values*/ return a; }
int FixB(int& a, int b, int& c) { /*fix a b c values*/ return b; }
int FixC(int& a, int& b, int c) { /*fix a b c values*/ return c; }
I suppose there should also be some kind of flag indicating that fix was already done. I am not sure if this is actually correct c++.
I know the best solution is to actually catch exception.
Consider interposing a class between
DerivedandBase:In C++11 you can use a delegating constructor of
Derived: