When is the constructor called in java and c++? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

When is the constructor called in java and c++?

is the constructor called using the new keyword or when the object is declared, e.g. myclass newobj;. Is there a difference between the two languages?

12th Jul 2017, 9:23 PM
Handy
Handy - avatar
2 Answers
+ 2
Human Handy = new Human; // Constructor is called for the Handy human.
12th Jul 2017, 11:57 PM
Keto Z
Keto Z - avatar
+ 1
Thank you for all of your reply. I just want to add the difference between languages that I found: In C++, the object is created and constructor is called when declaring the object. It could also be created using new keyword but requires you to delete it later manually. myclass myobj; myclass myobj = new myclass(); In Java, constructor is called with the new keyword myclass myobj = new myclass(); In Python, constructor is called by assigning it to a variable myobj = myclass();
17th Jul 2017, 8:47 AM
Handy
Handy - avatar