c++boost-function

warning: derived class's member variable is initialized after base class


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


Solution

  • 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.