views:

372

answers:

7

I'm preparing for an exam in Java and one of the questions which was on a previous exam was:"What is the main difference in object creation between Java and C++?"

I think I know the basics of object creation like for example how constructors are called and what initialization blocks do in Java and what happens when constructor of one class calls a method of another class which isn't constructed yet and so on, but I can't find anything obvious. The answer is supposed to be one or two sentences, so I don't think that description of whole object creation process in Java is what they had in mind.

Any ideas?

+12  A: 

What is the main difference in object creation between Java and C++?

Unlike Java, in C++ objects can also be created on the stack.

For example in C++ you can write

Class obj; //object created on the stack

In Java you can write

Class obj; //obj is just a reference(not an object)
obj = new Class();// obj refers to the object
Prasoon Saurav
I would argue that this is the memory allocation that happens before object creation. Does it really count?
Space_C0wb0y
I'm not sure that they are asking about memory allocation, but on the other hand, I'm not sure that they aren't asking about memory allocation.
AndrejaKo
I would extend this answer to consideration of placement-new ... C++ allows creating the object anywhere - automatically on stack or heap, or even a memory location YOU specify. On Java, this is all done by the JVM... and it's always on the heap.
Deep-B
@Deep-B: Placement new is a very advance technique. I would not expect an average C++ user to know how to use it let alone a student who is studying the difference between C++ and Java
Martin York
+2  A: 

I would answer: C++ allows creating an object everywhere: on the heap, stack, member. Java forces you allocate objects on the heap, always.

ybungalobill
Same as @Prasoon: Allocation happens before object creation, so is this really what is asked for?
Space_C0wb0y
@Space: at least in Java you can't have memory allocation without object creation (and even in C++ those two usually go together), so I'd argue that info still applies.
Joachim Sauer
Well, unlike C++, in java you can't separate allocation from creation.
ybungalobill
@Joachim: This comment might itself be a very good answer to this question.
Space_C0wb0y
@Space_C0wb0y: I'd say memory allocation is part of object creation, the other art being initialisation.
JeremyP
+8  A: 

Besides heap/stack issues I'd say: C++ constructors have initialization lists while Java uses assignment. See http://www.parashift.com/c++-faq-lite/ctors.html#faq-10.6 for details.

LumpN
+1 This is something "Java to C++ migrates" often fail to understand.
FredOverflow
+2  A: 

In Java, the Java Virtual Machine (JVM) that executes Java code has to might1 log all objects being created (or references to them to be exact) so that the memory allocated for them can later be freed automatically by garbage collection when objects are not referenced any more.

EDIT: I'm not sure whether this can be attributed to object creation in the strict sense but it surely happens somewhen between creation and assignment to a variable, even without an explicit assignment (when you create an object without assigning it, the JVM has to auto-release it some time after that as there are no more references).

In C++, only objects created on the stack are released automatically (when they get out of scope) unless you use some mechanism that handles this for you.

1: Depending on the JVM's implementation.

Archimedix
This is actually implementation dependend. As far as i know, most garbage collector will walk the object graphs from the collection root, not increment a reference counter.
Guillaume
Thanks Guillaume, I've updated my answer to point that out.
Archimedix
+13  A: 

In addition to other excellent answers, one thing very important, and usually ignored/forgotten, or misunderstood (which explains why I detail the process below):

  • In Java, methods are virtual, even when called from the constructor (which could lead to bugs)
  • In C++, virtual methods are not virtual when called from the constructor (which could lead to misunderstanding)

What?

  • Let's imagine a Base class, with a virtual method foo().
  • Let's imagine a Derived class, inheriting from Base, who overrides the method foo()

The difference between C++ and Java is:

  • In Java, calling foo() from the Base class constructor will call Derived.foo()
  • In C++, calling foo() from the Base class constructor will call Base.foo()

Why?

The "bugs" for each languages are different:

  • In Java, calling any method in the constructor could lead to subtle bugs, as the overridden virtual method could try to access a variable which was declared/initialized in the Derived class.

Conceptually, the constructor’s job is to bring the object into existence (which is hardly an ordinary feat). Inside any constructor, the entire object might be only partially formed – you can know only that the base-class objects have been initialized, but you cannot know which classes are inherited from you. A dynamically-bound method call, however, reaches “forward” or “outward” into the inheritance hierarchy. It calls a method in a derived class. If you do this inside a constructor, you call a method that might manipulate members that haven’t been initialized yet – a sure recipe for disaster.

Bruce Eckel, http://www.codeguru.com/java/tij/tij0082.shtml

  • In C++, one must remember a virtual won't work as expected, as only the method of the current constructed class will be called. The reason is to avoid accessing data members or even methods that do not exist yet.

During base class construction, virtual functions never go down into derived classes. Instead, the object behaves as if it were of the base type. Informally speaking, during base class construction, virtual functions aren't.

Scott Meyers, http://www.artima.com/cppsource/nevercall.html

paercebal
Great answer!!! ... interesting information ... thanx for sharing :)
Hemant
+1 I stumbled upon this on my own... my parents told me about many dangerous things out there but never told me about *that*, and I had to look it up on the internet.
Archimedix
paercebal
I can't really say which answer is the best for this question, so I'll accept this one because it has the highest amount of up-votes at the moment.
AndrejaKo
+1  A: 

There is one main design difference between constructors in C++ and Java. Other differences follow from this design decision.

The main difference is that the JVM first initializes all members to zero, before starting to execute any constructor. In C++, member initialization is part of the constructor.

The result is that during execution of a base class constructor, in C++ the members of the derived class haven't been initialized yet! In Java, they have been zero-initialized.

Hence the rule, which is explained in paercebal's answer, that virtual calls called from a constructor cannot descend into a derived class. Otherwise uninitialized members could be accessed.

Sjoerd
A: 

Assuming that c++ uses alloc() when the new call is made, then that might be what they are looking for. (I do not know C++, so here I can be very wrong)

Java's memory model allocates a chunk of memory when it needs it, and for each new it uses of this pre-allocated area. This means that a new in java is just setting a pointer to a memory segment and moving the free pointer while a new in C++ (granted it uses malloc in the background) will result in a system call.

This makes objects cheaper to create in Java than languages using malloc; at least when there is no initialization ocuring.

In short - creating objects in Java is cheap - don't worry about it unless you create loads of them.

Knubo