|
-
June 11th, 2009, 10:17 AM
#6
Re: Instantiating before the body is called?
 Originally Posted by Paul McKenzie
Also, please note:
All member variables of the class/struct are created by the compiler before the body of the constructor is called. If you have a member where it doesn't have a default constructor, you must tell the compiler how to create this member. You do this by supplying the member on the initialization list, along with the appropriate parameters to create the member successfully.
Code:
#include <string>
class foo
{
std::string x;
};
int main()
{
foo f;
}
So when f is created, when does the compiler invoke the constructor for the member variable "x"? The answer is in my first paragraph of this post. If std::string didn't have a default constructor, then you must tell the compiler how to construct it using the initialization list.
Regards,
Paul McKenzie
Thanks Paul. That was very helpful.
Continuing on this theme, lets say I have 2 members, one with and one without default constructor. The one without a default constructor MUST appear in the initializer list, however, the other NEED NOT, but for good programming practice, it is recommended. Is that right?
Also, when we say "compiler creates the members", what do you mean? are objects created and stored in obj and exe files as binaries? I thought objects are created at runtime on stack or on heap?
Thanks,
sgiri
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|