I have been using C++ and Java for several years now. One thing which I can't seem to understand is that why do we need to provide constructors of a class a name? For instance, if I have to define a class FOO
in C++/Java, I'll be forced to provide FOO
as the constructor name. However, since constructor is never explicitly called, what is the sense in compiler forcing me to provide it a name after all.
The abstraction paradigm dictates, we hide unnecessary details from programmers. This is the reason, constructors don't have a return type, since it's already well-defined what a constructor has to return. In the same spirit, why can't we just give a generic name to constructors of all classes - for instance anything meaningful, like initialize()
or maybe just nothing and just arguments ( [arg [,arg]] )
I hope, I'm able to express myself. If someone have any definitive answers, kindly let me know.
It is called when an instance of the class is created. At the time of calling the constructor, memory for the object is allocated in the memory. It is a special type of method which is used to initialize the object. Every time an object is created using the new() keyword, at least one constructor is called.
Every class object is created using the same new keyword, so it must have information about the class to which it must create an object. For this reason, the constructor name should be the same as the class name.
The name of the constructor must be the same as the name of the class and, if you provide more than one constructor, the arguments to each constructor must differ in number or in type from the others. You do not specify a return value for a constructor.
class A { into x; public: A(); //Constructor }; While defining a constructor you must remember that the name of constructor will be same as the name of the class, and constructors never have return type.
In C++ constructors do not have names(C++03 12.1), however since constructors are essentially defined as functions, it was logical to name them in some way.
Naming them anything other than the class name would have added new keywords and hence eventually they were named same as the class name.
In short, It was a logical decision which avoided new keywords and at the same time ensured intuitiveness.
From the C++ standard (12.1) (emphasis mine):
Constructors do not have names. A special declarator syntax is used to declare or define the constructor. The syntax uses:
- an optional decl-specifier-seq in which each decl-specifier is either a function-specifier or constexpr,
- the constructor’s class name, and
- a parameter list
In C++, you are not providing a name, you are writing special syntax which was decided by the language creators to declare a constructor.
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