+ 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){} };
4 Respuestas
+ 2
and what if you wanna initialise the variable with different values for different objects of class?
+ 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.
0
For better understanding we use constructure to clean the code and for fast compilation.