views:

107

answers:

3

Hi everyone.

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

+6  A: 

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:

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

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.

GMan
Thanks, the exception part cleared some doubts. Is it ok to do thisclass C{ float vx();float vy();public:...};?
Tom
... meaning "and so on", not an incorrect use of varargs.
Tom
@Tom: It's *okay* but not what you want. (Hint: those look like functions to me :).) Unfortunately, there is no simple way to say "hey, make this zero so I don't have to write a constructor".
GMan
@GMan: Thanks. Thats right, they do look like functions. I'm getting some sleep ASAP.
Tom
A: 

By the time the control reaches the constructor all the variables would have got default values.

Thiyaneshwaran S
Eh, an aggregate gets no initialization, it's value is indeterminate.
GMan
A: 

I can think of one specific case where this might bite you. If C is intended to be a base class, allowing a reference to it to escape to non-member functions may cause surprise. In the base class case constructors are more special because the derived class hasn't been constructed yet and virtual functions call the base class rather than the derived class. Non member functions may not be expecting to get an object in this state, and because they don't look like constructors it would be easy to introduce bugs by forgetting that.

It still isn't undefined behaviour though - just surprising defined behaviour :)

Stewart