While designing the class, I always get confused what to put in Constructor and what to put in Init. So could you please give your opinion on this. Please find my queries below.
- Should class have separate Init function?
- If Yes, what should go in the constructor of the class and Init function of the class.
From my understanding, I generally tend to always have Init function(for some lazy initialization). For example, if I have to design ConnectionPool class then I would something like this.
class ConnectionPool
{
string _host;
bool _isInit; //For separate Init, we need this
public:
ConnectionPool(string host)
:_host(host),
_isInit(false)
{}
void Init();
bool isInit(){return _isInit;}
}
//This will actually make connections
ConnectionPool::Init()
{
//Create few connections
//if successful
_isInit=true;
}
int main()
{
ConnectionPool cp("host");
//Few other init & wait for request
//Now I have the request
if(cp.isInit() == false)
cp.Init();
}
But lately, I can not resists having separate Init function. So could you please tell me what is the good practice.
Usually
initfunctions are private and are just used by contructors. This is so that you do not need the same common code in the various contructors and hence less prone to code bloat and errors.