Constructors in programming languages

Why isn't constructor considered a member for a class?
Is there any specific reason?

Thank you and welcome.

+4
source share
6 answers

I reject the background of the question. A constructor is a member of a class or structure in C #.

I refer to section 3.4.4 ("Class Members") of the C # specification, which lists the members of a class:

A class declaration may contain declarations of constants, fields, methods, properties, events, indexers, operators, instance constructors, destructors, static constructors, and types.

Clearly, constructors are members of a class. Why do you think the constructor is not a member? Who told you that a lie?

+9
source

Members are inherited to subclasses. Constructors should not be inherited, so they are not considered members.

Constructors are not inherited because their task is to initialize the attributes of their particular class. Any subclass must initialize its additional attributes, and for this task it needs its own constructor that knows about additional attributes.

In addition, each constructor must call one of its superclass constructors directly or indirectly as its first action to give the superclass a change to initialize.

+8
source

In C ++, constructors are certainly considered members of the class — the C ++ standard describes them in the section entitled “Special Member Functions”.

+7
source

As I see it, a constructor is not a method, but a lifecycle hook provided by Java (another lifecycle hook ends). This gives you the opportunity to do what would be necessary before any method could be called on the object. Thus, there is a clear distinction between methods and constructor, so even language specifications have it, but the intention is not completely clear from the function.

+2
source
+1
source

Since Eric points out , in C # constructors are considered members of the class. In fact, it’s just a class method with additional metadata used by the compiler and the runtime, so the constructor method is called when the object is created.

Although he does not say why, according to the Java Language Specification, Second Edition , constructors, static initializers, and instance initializers are not members.

0
source

Source: https://habr.com/ru/post/1309182/


All Articles