Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ vs Java constructors

According to John C. Mitchell - Concepts in programming languages,

[...] Java guarantees that a constructor is called whenever an object is created. [...]

This is pointed as a Java peculiarity which makes it different from C++ in its behaviour. So I must argue that C++ in some cases does not call any constructor for a class even if an object for that class is created.

I think that this happens when inheritance occurs, but I cannot figure out an example for that case.

Do you know any example?

like image 958
hoheinzollern Avatar asked Dec 08 '09 09:12

hoheinzollern


People also ask

Does C language have constructors?

A Constructor in C is used in the memory management of C++programming. It allows built-in data types like int, float and user-defined data types such as class. Constructor in Object-oriented programming initializes the variable of a user-defined data type. Constructor helps in the creation of an object.

Is C better than Java?

C is a procedural, low level, and compiled language. Java is an object-oriented, high level, and interpreted language. Java uses objects, while C uses functions. Java is easier to learn and use because it's high level, while C can do more and perform faster because it's closer to machine code.

What is difference between Java constructor and method?

A Constructor is a block of code that initializes a newly created object. A Method is a collection of statements which returns a value upon its execution. A Constructor can be used to initialize an object. A Method consists of Java code to be executed.


1 Answers

If your class defines at least one constructor, then the language will not allow you to construct an object of that type without calling a constructor.

If your class does not define a constructor, then the general rule is that the compiler-generated default constructor will be called.

As other posters have mentioned, if your class is a POD type, there are cases where your object will be left uninitialized. But this is not because the compiler "didn't call the constructor". It is because the type has no constructor (or it has one which does nothing), and is handled somewhat specially. But then again, POD types don't exist in Java, so that can't really be compared.

You can also hack around things so that the constructor is not called. For example, allocate a buffer of char's, take a pointer to the first char and cast it to the object type. Undefined behavior in most cases, of course, so it's not really "allowed", but the compiler generally won't complain.

But the bottom line is that any book which makes claims like these without being very explicit about which specific corner cases they're referring to, is most likely full of garbage. Then again, most people writing about C++ don't actually know much about the language, so it shouldn't be a surprise.

like image 146
jalf Avatar answered Sep 21 '22 07:09

jalf