Why do we need constructor to initialize the variables? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Why do we need constructor to initialize the variables?

Why do we need constructor to initialize the variables if we can simply do this when declaring the variable? for example we can do this..... class sample { int i=0,j=0; }; then why to do this..... class sample { int i,j; public: sample():x(0),y(0){} };

7th Jun 2020, 8:02 AM
Abhishek Dimri
Abhishek Dimri - avatar
3 Answers
+ 2
and what if you wanna initialise the variable with different values for different objects of class?
7th Jun 2020, 8:11 AM
Abhay
Abhay - avatar
+ 1
Traditionally, you couldn’t initialize variable directly in class and had to use a constructor. But the latest spec, C++14, specifies that you can do in-class initialization, and your compiler will support that feature if it is fully C++14 complete. If you use BOTH in-class initialization and constructors, the action of the constructor will override the intialization.
8th Jun 2020, 11:34 AM
Ayushi Patel
Ayushi Patel - avatar
0
For better understanding we use constructure to clean the code and for fast compilation.
8th Jun 2020, 6:45 AM
Naveed
Naveed - avatar