calling member functions from an initialiser list

Discussion in 'C++' started by John Harrison, Jun 25, 2003.

  1. What are the rule concerning calling member functions from an initialiser
    list? Suppose I have

    class C : public B
    C() : x(), y(f()), z() {}
    Y f();
    X x;
    Y y;
    Z z;

    B, X, Y, Z are other classes.

    What am I allowed to do in C::f()? Presumably I'm not allowed to access C::y
    or C::z since they haven't been constructed yet, what about C::x, and what
    about members of the base class B? Any other gotchas in this situation?

    John Harrison, Jun 25, 2003
    1. Advertisements

  2. The rule is that you may do that, but (a) it will resolve statically
    (no virtual calls), and (b) the function should not try to use any
    parts of the object (members and base classes) that haven't been
    constructed yet.

    Perhaps in your case it's better to make 'f' static?.. And if you need
    to use 'x' there, just pass it as an argument...

    Victor Bazarov, Jun 25, 2003
    1. Advertisements

  3. John Harrison escribió:
    The base class is constructed before any members. x is constructed, then
    you can use it.

    =?iso-8859-1?Q?Juli=E1n?= Albo, Jun 25, 2003
    1. Advertisements

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments (here). After that, you can post your question and our members will help you out.