[Solved] Why need new operator in java but not in c++


C++ and Java have similar syntax but not always means the same.

In Java all objects are references, so when you’re doing Classname obj; you’re creating a empty reference to an object, so you need to assign something to it.

Classname obj;
//here obj is pointing to nothing.

obj = new Classname();
//here obj is pointing to a new Classname object

The same behavior can be done in C++ with pointers

Classname* obj;
//here obj is pointing to nothing.

obj = new Classname();
//here obj is pointing to a new Classname object

Now, Classname obj; in C++ is very different. It creates the object in the stack, in simple words, the object behaves like fundamentals types (int, bool, float, etc). This behavior isn’t supported in Java due it’s garbage collected nature.

1

solved Why need new operator in java but not in c++