Suppose I have these two classes
class base_size
{
public:
int size()
{ return 5; }
};
class base_implement
{
public:
base_implement(int s) : _vec(s)
{
cout << "size : " << _vec.size() << endl;
}
private:
vector<float> _vec;
};
If I were to inherit from both of these would it be alright to call one of these classes member function in the other’s constructor? For example
class derived :
public base_implement,
public base_size
{
public:
derived() : base_size(), base_implement(size())
{
// Is this OK?
// If derived is not yet constructed can I access this->size() ?
// Works in VC++. Not sure about other compilers.
}
};
In principle that’s fine. The base subobjects and the member objects are constructed before the derived constructor body runs, so you can call the member function without problems. You can even call your own member functions in the constructor; you just have to make sure that they don’t rely on anything that comes later in on the same constructor.
Just make sure to call the base initializers in the correct order, i.e. the order of their declaration, and/or fix your class definition: For
base_size::size()you want thebase_sizesubobject to be fully constructed, so it has to come first.