calling member functions from an initialiser list

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • John Harrison

    calling member functions from an initialiser list

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

    class C : public B
    {
    public:
    C() : x(), y(f()), z() {}
    private:
    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?

    thanks,
    john


  • Victor Bazarov

    #2
    Re: calling member functions from an initialiser list

    "John Harrison" <john_andronicu s@hotmail.com> wrote...[color=blue]
    > What are the rule concerning calling member functions from an initialiser
    > list? Suppose I have
    >
    > class C : public B
    > {
    > public:
    > C() : x(), y(f()), z() {}
    > private:
    > 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[/color]
    C::y[color=blue]
    > 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?[/color]

    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


    Comment

    • Julián Albo

      #3
      Re: calling member functions from an initialiser list

      John Harrison escribió:
      [color=blue]
      > class C : public B
      > {
      > public:
      > C() : x(), y(f()), z() {}
      > private:
      > 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 accessC::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?[/color]

      The base class is constructed before any members. x is constructed, then
      you can use it.

      Regards.

      Comment

      Working...