How to ensure that a member variable is initialized before calling a class method

Posted by Omkar Ekbote on Programmers See other posts from Programmers or by Omkar Ekbote
Published on 2013-11-11T11:09:21Z Indexed on 2013/11/11 16:15 UTC
Read the original article Hit count: 178

Filed under:

There's a class with a parametrized constructor that initializes a member variable. All public methods of the class then use this member variable to do something.

I want to ensure that the caller always creates an object using the parametrized constructor (there is also a setter for this member variable) and then call that object's methods. In essence, it should be impossible for the caller to call any method without setting a value to the member variable (either by using the parametrized constructor or the setter).

Currently, a caller can simply make an object using the default constructor and then call that object's method - I want to avoid checking whether or not the member variable is set in each and every one of the 20-odd methods of the class (and throw an exception if it is not).

Though a runtime solution is acceptable (better than the one I mentioned above); a compile-time solution is preferable so that any developer will not be allowed to make that mistake and then waste hours debuggging it!

© Programmers or respective owner

Related posts about c++