Reputation:
www.fredosaurus.com
states this:
When an object of a class is created, C++ calls the constructor for that class. If no constructor is defined, C++ invokes a default constructor, which allocates memory for the object, but doesn't initialize it.
But I thought constructors are only responsible for initializing data members. Is my understanding incorrect?
Upvotes: 1
Views: 553
Reputation: 170064
To reiterate my comment, that tutorial is wrong. The storage for the object itself is not the responsibility of the constructor. If you look at the C++ standard definition of object lifetime [basic.life]/1:
The lifetime of an object or reference is a runtime property of the object or reference. An object is said to have non-vacuous initialization if it is of a class or aggregate type and it or one of its subobjects is initialized by a constructor other than a trivial default constructor. [ Note: Initialization by a trivial copy/move constructor is non-vacuous initialization. — end note ] The lifetime of an object of type T begins when:
storage with the proper alignment and size for type T is obtained, and
if the object has non-vacuous initialization, its initialization is complete,
You'll see that obtaining the storage is a separate item in the description of the objects lifetime. And for a good reason, since storage can be obtained in a multitude of ways:
operator new
. Again, not something the c'tor will do.The constructor is always operating on storage (however obtained) to make an object come into existence there.
The quote you got from the site is wrong two-fold. Since a default c'tor could very well initialize the object to have valid state. Consider this:
struct foo {
std::string a;
std::string b;
};
There is no user defined c'tor, so a compiler generated one will be synthesized. And you can be certain that it will default initialize the two strings into a valid state (as empty strings).
Upvotes: 5