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

984 Views Asked by At

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

3

There are 3 best solutions below

2
NathanOliver On BEST ANSWER

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.

0
Roman Dobrovenskii On

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();
}
0
slashmais On

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
};