Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Constructors in Programming languages

Why constructor is not considered as member of a class ?
Is there any specific reason ?

Thanks and regards.

like image 674
Saurabh Gokhale Avatar asked Nov 28 '22 19:11

Saurabh Gokhale


2 Answers

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

I refer you to section 3.4.4 ("Class members") of the C# specification, which enumerates 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 believe that a constructor is not a member? Who told you that lie?

like image 189
Eric Lippert Avatar answered Dec 14 '22 02:12

Eric Lippert


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

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

Also, each constructor must call one of its superclass constructors directly or indirectly as its first action, to give the superclass a change for initialization.

like image 23
Christian Semrau Avatar answered Dec 14 '22 01:12

Christian Semrau