- 1

Why do you even need constructors?

Why are constructors even a thing? You could just define a function and it would work the same. What is the use of a constructor?

10th Jul 2018, 10:21 AM
Yash Saurabh
1 Answer
+ 2
Basically we want the object to be in a valid state as soon as you declare it. So as soon as you write e.g. Dog waldo; the waldo object is ready to go. You could write a .initialize function or so but if you forget to call it your program blows up. Maybe it's more obvious with destructors; if you had to call all of them manually, C++ code would be a bugfest! Almost every class will do something when a nw object is created, so we put that into the constructor. Also it's just shorter to write of course, and more consistent. You don't do int x; x.initialize(); so why should you with classes?
10th Jul 2018, 10:34 AM
Schindlabua
Schindlabua - avatar