Why we use constructor in c++?? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Why we use constructor in c++??

i know they are used to initialize objects! but even without constructors , objects work fine . so what is the need to write those extra lines of code?

18th Sep 2018, 9:09 AM
Bunny
Bunny - avatar
1 Answer
+ 1
An object may enter an invalid state when instantiated if it's constructor isn't implemented properly. Say, a FractionalNum object with 2 attributes: nominator and denominator. What would you do if when initialized, the denominator field is set to 0? The constructor is there to ensure the object is error-free and ready to enter it's life cycle. Constructors are also used in memory management, where different types of initialization are expected to invoke their corresponding constructors (move constructor, copy constructor, etc.) to increase performance.
18th Sep 2018, 9:43 AM
Hoàng Nguyễn Văn
Hoàng Nguyễn Văn - avatar