calling member functions from an initialiser list

J

John Harrison

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
 
V

Victor Bazarov

John Harrison said:
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?

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
 
?

=?iso-8859-1?Q?Juli=E1n?= Albo

John Harrison escribió:
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?

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

Regards.
 

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. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top