Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
303 views
in Technique[技术] by (71.8m points)

c# - Why constructors will always have same name as of class and how they are invoked implicitly?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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:

  1. allocate memory
  2. call constructor
  3. use object
  4. call destructor/finalizer
  5. 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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...