简体   繁体   中英

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?

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.

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.

Seem to me that having sepearte keywords for declaring constructor(s) would be "better", as it would remove the otherwise unnecessary dependency to the name of the class itself.

Then, for instance, the code inside the class could be copied as the body of another without having to make changes regarding name of the constructor(s). Why one would want to do this I don't know (possibly during some code refactoring process), but the point is one always strives for independency between things and here the language syntax goes against that, I think.

Same for destructors.

One of the good reasons for constructor having the same name is their expressiveness. For example, in Java you create an object like,

MyClass obj = new MyClass();  // almost same in other languages too

Now, the constructor is defined as,

class MyClass {
  public MyClass () {... }
}

So the statement above very well expresses that, you are creating an object and while this process the constructor MyClass() is called.

Now, whenever you create an object, it always calls its constructor. If that class is extend ing some other Base class, then their constructor will be called first and so on. All these operations are implicit. First the memory for the object is allocated (on heap) and then the constructor is called to initialize the object. If you don't provide a constructor, compiler will generate one for your class.

In C++, strictly speaking constructors do not have names at all. 12.1/1 in the standard states, "Constructors do not have names", it doesn't get much clearer than that.

The syntax for declaring and defining constructors in C++ uses the name of the class. There has to be some way of doing that, and using the name of the class is concise, and easy to understand. C# and Java both copied C++'s syntax, presumably because it would be familiar to at least some of the audience they were targeting.

The precise flow of execution depends what language you're talking about, but what the three you list have in common is that first some memory is assigned from somewhere (perhaps allocated dynamically, perhaps it's some specific region of stack memory or whatever). Then the runtime is responsible for ensuring that the correct constructor or constructors are called in the correct order, for the most-derived class and also base classes. It's up to the implementation how to ensure this happens, but the required effects are defined by each of those languages.

For the simplest possible case in C++, of a class that has no base classes, the compiler simply emits a call to the constructor specified by the code that creates the object, ie the constructor that matches any arguments supplied. It gets more complicated once you have a few virtual bases in play.

I want to know that why the name of constructor is always same as that of class name

So that it can be unambigously identified as the constructor.

and how its get invoked implicitly when we create object of that class.

It is invoked by the compiler because it has already been unambiguously identified because of its naming sheme.

Can anyone please explain the flow of execution in such situation?

  1. The new X() operator is called.
  2. Memory is allocated, or an exception is thrown.
  3. The constructor is called.
  4. The new() operator returns to the caller.

the question is why designers decided so?

Naming the constructor after its class is a long-established convention dating back at least to the early days of C++ in the early 1980s, possibly to its Simula predecessor.

The convention for the same name of the constructor as that of the class is for programming ease, constructor chaining, and consistency in the language.

For example, consider a scenario where you want to use Scanner class, now what if the JAVA developers named the constructor as xyz!

Then how will you get to know that you need to write :

Scanner scObj = new xyz(System.in) ;

which could've have been really weird, right! Or, rather you might have to reference a huge manual to check constructor name of each class so as to get object created, which is again meaningless if you could have a solution of the problem by just naming constructors same as that of the class.

Secondly, the constructor is itself created by the compiler if you don't explicitly provide it, then what could be the best name for constructor could automatically be chosen by the compiler so it is clear to the programmer! Obviously, the best choice is to keep it the same as that of the class.

Thirdly, you may have heard of constructor chaining, then while chaining the calls among the constructors, how the compiler will know what name you have given to the constructor of the chained class! Obviously, the solution to the problem is again same, KEEP NAME OF THE CONSTRUCTOR SAME AS THAT OF THE CLASS.


When you create the object, you invoke the constructor by calling it in your code with the use of new keyword(and passing arguments if needed) then all superclass constructors are invoked by chaining the calls which finally gives the object.

Thanks for Asking.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM