Yes, it is recommended to do this, mainly for the reason that you have already mentioned.
On the other hand, you should ask yourself if you need a setter at all, and not directly perform checks inside the constructor. The reason I write this is because setters generally lead to a mutable state that has many flaws, rather than immutable classes. However, sometimes they are required.
Another recommendation: if your class variable is an object, and you can change the constructor of this object, you can put a check in the constructor of this object:
class MyFoo { public: MyFoo(int value) { if (value < 42) { throw invalid_argument{"Foo < 42."}; } v = value; } private: int v; }
This will allow you to use the initialization list in the constructor of your Test class:
Test(int foo) : foo(foo) {}
However, now the check is a property of the variable class and is no longer one of the owning classes.
source share