-9

I want to know whether int main() function be called a constructor function since it nearly works same as a constructor function of a class?

And if yes, then what is the class name it belongs to?

Edit: The reason why I think main() works nearly same as constructor function is that whenever we execute a programme the first thing which gets executed is the main function.. Similarly a constructor function executes first whenever we define a variable with data type as user defined class

  • What...? `main` is not a constructor... not at all... – Andrew Li Apr 02 '17 at 03:26
  • 1
    No. `int main()` is not a constructor (it doesn't **construct** anything), and it does not belong to any class. – Ken White Apr 02 '17 at 03:27
  • "Nearly works the same as a constructor" – in what way? I don't see much in common, but if you explain why you think they're similar, it might help others to explain why they're not. – Wyzard Apr 02 '17 at 03:31
  • Sorry guys, I think this community is not for me. As most of the questions I ask here are either downvoted or not voted at all.. I should just ask to teachers – Shivam-dev Apr 02 '17 at 04:39

2 Answers2

2

Can main() function be called a constructor function

No

A class constructor is a member-funtion. A member function is different from a non-member function which int main() is.

Actually a Constructor is a special kind of member-function that has no name and no address. This is responsible for creating objects. Objects can be created an "infinite" number of times in your program.

While main() is the function that starts up your program and you are not permitted to call main() else you invoke Undefined Behavior

Community
  • 1
  • 1
WhiZTiM
  • 21,207
  • 4
  • 43
  • 68
1

From reference:

main() "is a global function named main, which is the designated start of the program".[1]

So it is not part of a class, not a member method, hence the method CANNOT be a constructor. Rememember that C++ is a multiparadigm language. It includes an object oriented approach, but it does not need it to function. Java or C# are also multiparadigm, but they are mainly class and OOP based. For instance, in Java and C# you need to have classes and objects to create a "Hello World" program.

Santiago Varela
  • 2,199
  • 16
  • 22