The passage means that, if you have an Initialise()
function, someone might forget to call it. It is not "guaranteed to be used", because you cannot control people. On the other hand, you cannot "forget" to call a constructor, because you never call a constructor: the computer does that for you when you instantiate your object.
Of course, that doesn't mean that the constructor is guaranteed to be properly written; that's still down to you. In the case of a class like std::string
, though, it's pretty hard to get that wrong as it'll at least be default-constructed if you do not write code to do something else instead.
That happens whether or not you have an Initialise()
function that's supposed to be called later, but if you did put some more complex initialisation in your constructor then you can be assured that this code will run.
// Bad! People can forget to call Initialise, so the string might stay empty
class Foo
{
public:
void Initialise(const bool yesOrNo)
{
m_string = (yesOrNo ? "Yes!" : "No");
}
private:
std::string m_string;
};
// Good! You'll always have a value; no way around that
class Bar
{
public:
Bar(const bool yesOrNo)
: m_string(yesOrNo ? "Yes!" : "No")
{}
private:
std::string m_string;
};
Further reading:
s
. – Daniel Langr