I have a base class:
class CBase {
public:
virtual void SomeChecks() {}
CBase() {
/* Do some checks */
SomeChecks();
/* Do some more checks */
}
};
and a derived class:
class CDerived : public CBase {
public:
virtual void SomeChecks() { /* Do some other checks */ }
CDerived() : CBase() {}
};
This construction seems to be a bit weird but in my case this is required, because CBase does some checks and CDerived can mix some checks in between them. You can see it as a way to "hook" functions in the constructor. The problem with this construction is that while constructing CDerived first a CBase is constructed and there is no awareness of CDerived (so overloaded function SomeChecks() is not called).
I could do something like this:
class CBase {
public:
void Init() {
/* Do some checks */
SomeChecks();
/* Do some more checks */
}
virtual void SomeChecks() {}
CBase(bool bDoInit=true) {
if (bDoInit) { Init(); }
}
};
class CDerived : public CBase {
public:
virtual void SomeChecks() { /* Do some other checks */ }
CDerived() : CBase(false) { Init() }
};
This isn't really safe, because I want the constructor with the false parameter be protected, so only derived classes can call it. But then I'll have to create a second constructor (that is protected) and make it take other parameters (probably unused because is constructor is called when Init() does not have to be called).
So I'm quite stuck here.
EDIT Actually I want something like this:
class CBase {
protected:
void Init() { /* Implementation of Init ... */ }
CBase() { /* Don't do the Init(), it is called by derived class */ }
public:
CBase() { Init(); } // Called when an object of CBase is created
};
class CDerived : public CBase {
public:
CDerived() : CBase() { Init(); }
};
It seems to me it is impossible to have 2 constructors with the same arguments being protected and public?