Calling the non member function on the instance that was created

I am writing a class and this doubt has arisen. It's undef. behavior? On the other hand, I'm not sure if it's recommended or if it's good practice. Is this alone if I don't guarantee the 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

+2


a source to share


3 answers


This is completely normal. When you step into the body of a constructor, all members are initialized and ready to use. (The body must then complete any work that needs to be done to create a fully constructed object.)

But this is bad style. The best thing:

C::C() :
vx(), vy() // or vx(0), vy(0) if you prefer to be explicit
{}

      



And get rid of all the mess.


Exceptions have nothing to do with safety, constructors are free to throw. In fact, if you cannot successfully build the object, an exception is the preferred course of action.

+6


a source


By the time the control reaches the constructor, all variables will have default values.



0


a source


I can think of one specific case where this might bite you. If C is for a base class, allowing it to be referenced to escape into non-member functions might come as a surprise. In base class constructors, constructors are more specific because the derived class has not yet been built, and virtual functions call the base class, not the derived class. Non-member functions may not expect to receive an object in this state, and since they are not like constructors, it would be easy to introduce errors by forgetting about it.

Still not undefined behavior - just awesome definite behavior :)

0


a source







All Articles