I want to know that why the name of constructor is always same as that of class name and how its get invoked implicitly when we create object of that class. Can anyone please explain the flow of execution in such situation?
I want to know that why the name of constructor is always same as that of class name
Because this syntax does not require any new keywords. Aside from that, there is no good reason.
To minimize the number of new keywords, I didn't use an explicit syntax like this:
class X { constructor(); destructor(); }
Instead, I chose a declaration syntax that mirrored the use of constructors.
class X { X(); ~X();
This may have been overly clever. [The Design And Evolution Of C++, 3.11.2 Constructor Notation]
Can anyone please explain the flow of execution in such situation?
The lifetime of an object can be summarized like this:
In Java, step 1 always allocates from the heap. In C#, classes are allocated from the heap as well, whereas the memory for structs is already available (either on the stack in the case of non-captured local structs or within their parent object/closure). Note that knowing these details is generally not necessary or very helpful. In C++, memory allocation is extremely complicated, so I won't go into the details here.
Step 5 depends on how the memory was allocated. Stack memory is automatically released as soon as the method ends. In Java and C#, heap memory is implicitly released by the Garbage Collector at some unknown time after it is no longer needed. In C++, heap memory is technically released by calling delete
. In modern C++, delete
is rarely called manually. Instead, you should use RAII objects such as std::string
, std::vector<T>
and std::shared_ptr<T>
that take care of that themselves.
Why? Because the designers of the different languages you mention decided to make them that way. It is entirely possible for someone to design an OOP language where constructors do not have to have the same name as the class (as commented, this is the case in python).
It is a simple way to distinguish constructors from other functions and makes the constructing of a class in code very readable, so makes sense as a language design choice.
The mechanism is slightly different in the different languages, but essentially this is just a method call assisted by language features (the new
keyword in java and c#, for example).
The constructor gets invoked by the runtime whenever a new object is created.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With