Reputation: 9
I am developing quite a large Class whose objects require relatively costly validation if they are created by the public constructors, but for which the validation can be dispensed with for private constructors (since one can assume to be working with already-validated data).
In C++, is it possible to overload an operator (e.g. add or +) with the same signature in such a way that a different version of it is called from 'outside' the class (with input validation) and a different version is called from a member function (without the validation)?
For example, I'd like something like this:
class cBigClass
{
...
public:
friend cBigClass operator*(const int a, const cBigClass& C)
{
this->Validate(a);
cBigClass B = this->ComplicatedFunctionActuallyImplementingMultiply(a, C);
return B;
}
private:
friend cBigClass operator*(const int a, const cBigClass& C)
{
cBigClass B = this->ComplicatedFunctionActuallyImplementingMultiply(a, C);
return B;
}
private:
void DoSomethingPrivately()
{
int a = 1;
cBigClass C, D;
D = a*C; // Calls 'private' version of * without validation
}
};
...
// Elsewhere, e.g. in main()
int a = 2;
cBigClass A, B;
A = a*B; // Calls 'public' version of * with validation
A naive re-definition obviously throws a compiler error (g++), even when one is made public and one private. Both versions of such a function essentially have to have the same signature - is there a trick / hack for something like this? I would really like to avoid re-defining the operator code since it would lead to a lot of duplication.
Upvotes: 0
Views: 91
Reputation: 6805
Most problems can be solved with another level of indirection/abstraction.
You can define a base class which defines the core features as protected
. Then you can make your class to derived from that base class and redefine those functions with your validation steps.
An example is better than 1000 words:
class Base
{
protected:
double multiply(double a, double b) // Only accessible for derived classes
{
return a*b;
}
};
class MyClass : public Base
{
private:
void validate()
{
// Do whatever validation you want
}
public:
double multiply(double a, double b) // User exposed function with validation included
{
validate();
return Base::multiply(a, b);
}
};
Upvotes: 0