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:
- allocate memory
- call constructor
- use object
- call destructor/finalizer
- release memory
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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…