Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In which cases there is no constructor at all, even a default constructor?

In this book I am currently reading I ran across this:

A class doesn't need a constructor. A default constructor is not needed if the object doesn't need initialization.

Am I correct in inferring from the above that the compiler does not generate a default constructor for the class/structure in some cases? If yes, what are those cases? I will venture and say POD is probably one. Are there any other?

EDIT: I have changed the title as the original title gave the meaning that I asked when was a default constructor not defined instead of asking when does a class not have a constructor at all.

like image 213
Samaursa Avatar asked Aug 20 '11 13:08

Samaursa


People also ask

Do nothing constructor is also known as a default constructor?

A constructor that accepts no argument (parameter) is known as default constructor. default constructor is useful when we want to initialize class objects with some initial or default value.

What happens if there is no default constructor?

A default constructor is a constructor that either has no parameters, or if it has parameters, all the parameters have default values. If no user-defined constructor exists for a class A and one is needed, the compiler implicitly declares a default parameterless constructor A::A() .

Under what situations do you obtain a default constructor?

Every time an object is created using the new() keyword, at least one constructor is called. It calls a default constructor if there is no constructor available in the class. In such case, Java compiler provides a default constructor by default.

Is there always a default constructor?

If no user-declared constructors of any kind are provided for a class type (struct, class, or union), the compiler will always declare a default constructor as an inline public member of its class.


1 Answers

A class doesn't need a constructor. A default constructor is not needed if the object doesn't need initialization.

I think the author is talking about this situation:

some_type some_function () {
   POD_type this_is_intentionally_uninitialized;
   ...
}

Under some circumstances a constructor won't be called, period. As soon as you write a constructor you don't have a POD class, so now the constructor will be called.

Whether it is a good or bad thing to have an object running around that contains random, uninitialized data is a different question entirely.

like image 99
David Hammen Avatar answered Nov 03 '22 10:11

David Hammen