class a
{
object guest;
}
a::a() : guest(required_argument)
{
}
The problem is that I need the guest's constructor to be called AFTER creating class' a object. Is there a way to do it?
class a
{
object guest;
}
a::a() : guest(required_argument)
{
}
The problem is that I need the guest's constructor to be called AFTER creating class' a object. Is there a way to do it?
If you want to keep guest
as an object, no.
If you are free to make it a pointer, you can use lazy initialization for it.
object
has a constructor, it's not a POD, so the standard mandates it get initialized.
Jan 6, 2013 at 18:04
The real question is why do you need guest
's constructor to be called after a
's constructor?
guest
is a part of a
, so having its constructor invoked after a
's constructor is a contradiction in terms: an object is completely constructed only if all of its sub-objects are completely constructed, so completing the execution of a
's constructor implies completing the execution of guest
's constructor.
Of course, this doesn't mean you cannot just default-construct guest
during a
's construction and assign it a different value after or, if you do not want a guest
object to be constructed at all during a
's construction, to use a pointer (better if smart pointer) for modeling the association between a
and object
.
I suppose the reason for guest
to be constructed after host
is that some functionality of host
is required in the construction of guest
. In this case, you can out-source that functionality into a separate class which is constructed before guest
. Thus
class some_interface { /* some abstract functionality needed by guest::guest() */ };
class guest
{
public:
guest(some_interface const&); // calls pure virtual functions of some_interface
/* more stuff */
};
class host_interface : public some_interface
{
/* implements pure virtual methods of its base */
};
class host
{
host_interface _interface;
guest _guest;
public:
host(...)
: _interface(...)
, _guest(_interface)
{}
/* more stuff */
};
Note that the following naive implementation will fail
class host : some_interface
{
/* some_data */
guest _guest;
public:
host(...)
: some_data(...)
, _guest(*this)
{}
/* more stuff */
};
because this
is not yet constructed when passed to guest::guest()
, and the pure virtual functions will be called (I really had this bug once and got the run-time error "pure-virtual function called", even though the compiler should have been able to detect this).