user7129688
user7129688

Reputation:

Is the implicitly created default constructor responsible for allocating the objects memory?

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

Answers (1)

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:

  1. It may be static storage. So the c'tor can only initialize the object.
  2. It may be automatic storage, where again it's the run-time that manages it, not the c'tor, every time a scope is entered.
  3. It could be storage obtained by dynamic allocation, with the use of 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

Related Questions