Let's say I have this simple class with a const int member variable:
class MyClass{
public:
Myclass(int x, int y);
private:
const int importantNumber;
int anotherNumber;
};
MyClass::MyClass(int x, int y) :importantNumber{x}
{
this->anotherNumber = y;
}
Since int importantNumber
is const, I can only set it during the creation of the object by the constructor (with a member initialization list, as seen above).
Now, the question: how could I possibly add validation for argument x given to the constructor before actually creating importantNumber with that value? Is it possible to create a static int MyClass::validation(int a)
and use it on the member initialization list of the constructor like importantNumber{validation(x)}
?
Even if it's possible, is there a better way to do it?
You just add it.
MyClass::MyClass(int x, int y) : importantNumber{validate(x)}
{
this->anotherNumber = y;
}
The int validate(int original)
function can now return something other than x
or throw an exception or assert
or ask the user for confirmation, whichever you deem appropriate.
If it is just a simple check and you don't want to write a validate
function you can use a lambda:
MyClass::MyClass(int x, int y) :importantNumber{
[](int number){
assert(number > 0);
return number;
}(x)}
{
this->anotherNumber = y;
}
Although this can get a bit convoluted if you overdo it.