Michael Dorgan
Michael Dorgan

Reputation: 12515

Is it safe to call a function to initialize a class in a ctor list?

I have Angle class that I want initialized to a random value. The Angle constructor can accept an int from a random() function. Is it safe to place this call in the ctor list:

foo::foo() : Angle(random(0xFFFF)) {...}

or do I have to do it in the body of the constructor?

foo::foo() { Angle = Angle(random(0xFFFF)); ...}

If it matters, the foo class is derived from another class and does have virtual methods. In addition, no exception handling is allowed in our app.

Upvotes: 2

Views: 166

Answers (1)

Johannes Schaub - litb
Johannes Schaub - litb

Reputation: 506905

If random cannot throw (hard to believe that it could), there is no problem with this. Side effects are allowed in constructor initializers. It's good practice to do any initialization there, if it takes only little code.

Upvotes: 4

Related Questions