Non-pointer class member: how good is it? [duplicate]

  • A+

This question already has an answer here:

I have a non-pointer class member that I need to initialize in the constructor:

class Alerter {  protected:   Timer timer;  public:   Alerter(int interval); }; 

and then

Alerter::Alerter(int interval) {     timer = createTimer(interval); } 

(simplified code just to demonstrate the problem).

I have some doubts and concerns that timer probably is first created using its parameter-less constructor and later that instance is overwritten by the contents that the createTimer function returns.

How good is the approach? The possible answers could be:

  • The "empty timer" created by its parameter-less constructor is not actually created, as the compiler is smart enough to find we have never referenced it before overwriting the value.
  • The empty timer is created, but this is OK as well-written code should support a cheap parameter-less constructor for throwaway instances.
  • It's better to use pointers.

Which of these assumptions (or maybe something else) is the most correct?


timer is first default-constructed and then assigned. Of course you can make assumption about how cheap a Timer is to default-construct or about compiler optimization, but here you don't need this since can prevent default-construction by using an initializer list:

Alerter::Alerter(int interval) : timer(createTimer(interval)) { } 

This will work, unless your Timer class is copy-assignable but not copy-constructible, which would be weird.


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: