I’m writing a class, and this doubt came up. Is this undef. behaviour? On the other hand, I’m not sure its recommended, or if its a good practice. Is it one if I ensure no exceptions to be thrown in the init function?
//c.h
class C{
float vx,vy;
friend void init(C& c);
public:
C();
};
//c.cpp
C::C()
{
init(*this);
}
void init(C& c) //throws() to ensure no exceptions ?
{
c.vx = 0;
c.vy = 0;
}
Thanks in advance
It’s completely fine. Once you enter the body of the constructor, all the members have been initialized and they are ready to use. (The body is then to finish up any more work that needs to be done to create a fully constructed object.)
But it is poor style. Better is just:
And do away with all the mess.
Exceptions have nothing to do with safety, constructors are free to throw. In fact, if you can’t successfully construct an object then throwing an exception is the preferred course of action.