Stats Cruncher
Stats Cruncher

Reputation: 175

The compiler implicitly declares a default constructor

I am reading textbook "C++ Primer Plus, Prata"

A paragraph in chapter 10 catches my eye and confuses me.

Ch.10 Objects and classes:

enter image description here

It says

If you don't provide one, the compiler implicitly declares a default constructor and,...

I thought it should be

If you don't provide destructor, the compiler implicitly declares a default destructor and,...

Is the paragraph correct?

How should I explain that correctly?

Thank you

Upvotes: 1

Views: 104

Answers (1)

Cody Gray
Cody Gray

Reputation: 245012

The "one" part is correct. That's just a nuance of English grammar where you can refer to something in a dependent clause that comes later in the sentence. Think of it like a forward declaration! The "default constructor" part is actually a typo: it should be "default destructor", like you originally thought.

It should say this:

Because a destructor is called automatically when a class object expires, there ought to be a destructor. If you don't provide one [a destructor], the compiler implicitly declares a default destructor and, if it detects code that leads to the destruction of an object, it provides a definition for the destructor.

Here, "one" refers to "a destructor," which comes later in the sentence. Another key to understanding the sentence is keeping in mind the distinction between declaring a function and defining a function. The compiler always declares an implicit destructor if you don't provide one, but it only defines it if it needs it (that is, if that destructor is going to be called).

What makes it all the more confusing (and probably what led to the typo) is that all of this is equally true for constructors.

Let's see if we can improve on the paragraph:

Because the destructor will be called automatically when a class object goes out of scope, all classes must have a destructor. If you don't explicitly provide one, the compiler implicitly declares a default destructor. If the compiler detects code that leads to the destruction of an object, it also provides a default definition for the destructor. The same thing is true for constructors.

Upvotes: 3

Related Questions