struct A
{
A()
{
std::cout<<b()<<'\n';
}
int b()
{
return 5;
}
};
int main()
{
A a;
return 0;
}
i wonder how can function b() be called if < a > isn't created completely ... function b() must be called for an object, but object isn't created yet ... thanks :)
By the time you reach the opening { of the constructor, the constructors of all bases and members have already been executed.
It is OK to call most member functions and access any member subobject. It is not OK to call virtual member functions and expect them to do something special: nothing derived from A has been constructed yet. It is also a bad idea to pass a reference to this out of these member functions. it is Undefined Behavior to call a pure virtual member function from a constructor (§10.4/6)
yes, you are right....all the members before { are initialized :) ...but function must be called for an certain object .... but there is no object, which is created completely .... that's the question for me
You either have an object, or you don't. If you have one you can call it, if you don't have one you can't. Though honestly it's hard to comprehend what exactly you are trying to do.
It is true that the lifetime of an object starts when its constructor returns, but it's not true that the object cannot be used *at all* before its lifetime starts. It's just that there are restrictions, more severe before the constructor begins execution, less severe while it is executing.
§12.7/4 "Member functions, including virtual functions, can be called during construction or destruction"