Sellorio
Sellorio

Reputation: 1950

Initialiser list not in order

So I have made a class called Dictionary which inherits from a base IEnumerable and contains a member of type List. List has a const unsigned int& member that stores and exposes its item count.

This is Dictionary's constructor.

Dictionary() : _list(), IEnumerable(_list.Count)
{ }

I pass the const unsigned int& from the "initialised" list to IEnumerable. The problem is, that IEnumerable's initialiser is being called before _list's (the member of type List) so I'm passing in an invalid reference.

Is there any way to force the member _list to be initialised before the base class IEnumerable?

Upvotes: 1

Views: 70

Answers (2)

aschepler
aschepler

Reputation: 72271

Base classes are always initialized before direct members. (And in fact, the order of bases and members in a mem-initializer-list does nothing - the order is always determined from the class definition.)

One workaround is to move your member to another base class.

struct HasList {
    List _list;
    // Might want custom constructors here.
};

class Dictionary
    : private HasList,
      public IEnumerable
{
    // ...

(This is one of the few helpful uses of private inheritance.)

Upvotes: 4

TC1
TC1

Reputation: 1

  1. Base class constructors are called before inherited class' constructors.
  2. Members are initialized in the order they're declared (that is usually in the header file), the order of the initialization list is irrelevant.

Upvotes: 0

Related Questions