Do we need to make a constructor every time? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Do we need to make a constructor every time?

hi I'm reading OOP for the first time. I have a question, do we need to create a constructor every time?? why do we need to make constructor??

22nd Sep 2018, 1:26 PM
S.K
10 Answers
+ 2
No, it depends on your purpose. If you do not want to create objects, no need to use constructor
22nd Sep 2018, 1:30 PM
Muhd Khairul Amirin
Muhd Khairul Amirin - avatar
+ 2
If you have no costructor you can't instantiate any object (with the new keyword). You still can use static methods (methods that don't need to instantiate the class), but you can't do many things
22nd Sep 2018, 1:32 PM
Daniele Bonomi
Daniele Bonomi - avatar
+ 1
I'm sorry for asking silly questions but I'm kinda confuse, I have assignment question to make a class circle and find it's area. I did that and used a constructor, my colleague did it without creating any constructor. so what is the best practice??
22nd Sep 2018, 1:36 PM
S.K
+ 1
How did your colleague doesn't use any constructor? Did he done it in the main method (in java)? What language are you using?
22nd Sep 2018, 1:48 PM
Daniele Bonomi
Daniele Bonomi - avatar
+ 1
he did it in c++ which is the correct approach ?
22nd Sep 2018, 1:51 PM
S.K
+ 1
There is no wrong approach but I think the task asked you to have a costructor. You're surely right but I'm not sure you're colleague is right, too
22nd Sep 2018, 2:37 PM
Daniele Bonomi
Daniele Bonomi - avatar
+ 1
thank you all.
22nd Sep 2018, 2:38 PM
S.K
+ 1
There is always a constructor, but in some cases you don't have to write it explicitly If there is "no" constructor, there is actually an implicit one. Same with destructors.
22nd Sep 2018, 3:29 PM
Matthias
Matthias - avatar
+ 1
In Java if you specify no constructor then a default (no-arg) constructor is created by the compiler. (I expect something similar occurs in C++) so this may be the source of your confusion. The point of a constructor is to ensure an object is initialized into a correct/valid state, as specified by the programmer. If there is no need to specify this, then a default constructor is provided
22nd Sep 2018, 6:34 PM
Dan Walker
Dan Walker - avatar
0
No
22nd Sep 2018, 11:49 PM
Khalid Nadif
Khalid Nadif - avatar