BIG question

Dec 7, 2011 at 5:02pm
hello everyone ,,, i have a question in this code

#include<iostream>

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 :)
Last edited on Dec 7, 2011 at 5:02pm
Dec 7, 2011 at 5:25pm
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)

Last edited on Dec 7, 2011 at 5:32pm
Dec 7, 2011 at 7:00pm
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
Dec 7, 2011 at 7:16pm
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.
Dec 7, 2011 at 7:21pm
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"
Dec 7, 2011 at 7:46pm
If you declare the member function static you don't need to have an existing object to call it.
Topic archived. No new replies allowed.