Is it legal? If so, do you consider it as good coding practice?
I want to do something like this (nonessential details are not shown):
class ItemStorage {
int size() const;
};
class SpecialStorage : public ItemStorage {
public:
SpecialStorage (...) : ItemStorage(...), items(ItemStorage::size()) {...}
private:
int items;
};
I am pretty开发者_C百科 sure that it is OK if the method size is not virtual. What if it is virtual and the derived class doesn't overwrite it?
The general rule is that, during initialization, you must not access uninitialized parts of the object. As ItemStorage is already initialized when items gets initialized, calling size is indeed fine.
Even if size was virtual, and even if it was overwritten, it still would be fine: it would just call the base version (i.e. virtual methods only bind to the level which is under construction).
精彩评论