0

The title of the question is plain and simple. here is the code:

class xxx : public Scheduled
{
    long int _wait_time;
    boost::function< void() > _cb;
    mutable boost::mutex _mutex;

public:
    xxx(boost::function< void() > callback, unsigned int wait_time = 10000000)
    :_wait_time(wait_time),_cb(callback)
    ,Scheduled(Timer(_wait_time, 0))
    {
        this->stop();
    }
};

and although I respect the order of initialization, here is the warning I get:

---: In constructor ‘xxx::xxx(boost::function<void ()()>, unsigned int)’:
---: warning: ‘xxx::_cb’ will be initialized after
---: warning:   base ‘Scheduled’
---: warning:   when initialized here

Any thoughts? thank you

rahman
  • 4,820
  • 16
  • 52
  • 86

3 Answers3

2

You are initializing your derived class members befor you construct the base class.

xxx(boost::function< void() > callback, unsigned int wait_time = 10000000)
:_wait_time(wait_time),_cb(callback) <- derived class memebers
,Scheduled(Timer(_wait_time, 0)) <- Base class
{
    this->stop();
}

In C++ the base class must be constructed before the members of the derived class are initialized. So the warning is telling you that even though you have the base class initialization after the derived members it is going to construct the base class first.

If you change your code to

xxx(boost::function< void() > callback, unsigned int wait_time = 10000000)
:Scheduled(Timer(wait_time, 0))
                 ^ use wait_time instead of _wait_time
,_wait_time(wait_time),
,_cb(callback)
{
    this->stop();
}

You should no longer get a warning.

NathanOliver
  • 171,901
  • 28
  • 288
  • 402
  • thanks, but what if a base class initialization depends on derived members? for example you corrected my wait time. what if `_wait_time` was a class that had to be initialized before being supplied to base? – rahman Oct 16 '15 at 15:51
  • @rahman Then your design is broken. The base class must be initialized before any non static members of the class. Before the base class is initialized none of the derived class members have been initialized so you would be using garbage values. – NathanOliver Oct 16 '15 at 15:53
1

The base class constructor has to be the first one in the initialization list:

xxx(boost::function< void() > callback, unsigned int wait_time = 10000000)
:Scheduled(Timer(_wait_time, 0))
,_wait_time(wait_time),
,_cb(callback)
{
    this->stop();
}
Roman Dobrovenskii
  • 935
  • 10
  • 23
0

Adding to the other answers:
another reason for this warning can come about if your initialisers are in a different order than the order in which they appear in the class.

Example:

struct A { .. };
struct B { .. };
struct C
{
    A a;
    B b;
    C(..) : a(..), b(..) {}  // OK
    C(..) : b(..), a(..) {}  // Wreorder-warning
};
slashmais
  • 7,069
  • 9
  • 54
  • 80