Hi all,

I came to know that in Java or c++, constructor is executed only after the allocation of space....
Then what does an implicit default constructor(in c++) or default constructor in Java does....?
If we explicitly define our constructor then the initialization will be done according to our needs!
But what does an implicit or default constructor do?
Does it initialize house keeping data which are invisible to the programmer?
Is the actual allocation of space done by new operator or any implicit things....?
Thank you...

Dani AI

Generated

Short answer for : allocation and construction are two different steps. and pointed to the official docs; here’s a practical, language-by-language clarification.

In Java the JVM (the new operation) allocates the object and sets up the JVM bookkeeping (object header, class pointer, GC metadata). Before any constructor body runs the JVM also gives each field its language-default value (0, false, or null). If you declare no constructor, the compiler inserts a simple no-arg default constructor that just calls the superclass constructor and runs any instance initializers. That implicit constructor does initialization work (possibly nothing visible) and ensures superclass construction — it does not perform the raw allocation or low-level VM bookkeeping.

In C++ the allocation step (the memory request) is done by operator new (or by you if using placement new); after allocation the chosen constructor runs to initialize the object. If you provide no constructors the compiler will implicitly declare a default constructor; that generated constructor calls base-class and member constructors. Important difference: built-in members (ints, pointers) are not magically zeroed in all cases, so an implicit/default constructor may leave primitives indeterminate unless you explicitly initialize them. C++11 also gives you tools like =default, =delete, brace-init, and member initializers to control this precisely.

Practical rules:

  • If your class has invariants or manages resources, write an explicit constructor that sets them.
  • For simple POD-like objects you can rely on the compiler default, but be aware of C++'s uninitialized primitives.
  • In Java many frameworks need a visible no-arg constructor, so either leave the implicit one or provide a public no-arg ctor.

Example patterns:

/* Java: implicit default exists only if you write no constructors */
class A { int x; } // new A() -> x == 0 (JVM default)
/* C++: prefer explicit init for primitives */
struct S { int i = 0; }; // guarantees initialized state

Recommended Answers

All 2 Replies

The official Java documentation is always the definitive place to look. Here's what the Java Language Specification says about how an instance is created and initialised

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.