+ 2
Why variables initializes before the start of constructor body??
When we do initialization through constructor it's favorable to put it before the start bracket.
5 Réponses
+ 4
It sounds like you're asking about the benefit to using initializer lists. As you're probably aware, there are two ways to initialize member variables as part of our constructor:
MyClass::MyClass() : member_variable(value) { ... }
or
MyClass::MyClass() {
member_variable = value;
....
}
So, what's the benefit to using the former?
Consider the situation where member_variable is itself a class with its own constructor. By the time you enter the constructor body, all member variables have been initialized. Therefore, in the second case, member_variable will already have been initialized using the class' default constructor. Now if you assign a value to it in the constructor body, it has to call the constructor again, so overall you've constructed two objects when you only need one! This is wasteful, especially if your constructor performs some heavy operation, like allocating memory.
Now, when it comes to primitive types, it doesn't matter which approach you use, since they're not initialized (i.e., no constructor calls to worry about). Either approach is just as effective, but you might choose to use initializer lists regardless for the sake of consistency.
+ 8
because they they are accessible in the whole class
+ 4
Because we gives memory to them and we know contructor varible used by whole class and also by main.
+ 3
So we can use the variables if they are needed elsewhere and don't have to initialize them at the top of every constructor.
Think of them as default values.
class Person{
int legs = 2; // by default
int age; // not default
int yPos = 0;
boolean hasJumped;
// IIB, runs before constructor
{
jump();
}
Person(int age){
this.age = age;
// legs MUST be initialized for this to work:
if(hasJumped)
fall();
}
void jump(){
final float GRAVITY = 9.81f;
final int JUMP_POW = 100;
yPos += (JUMP_POW * legs) / GRAVITY;
/* used legs here
don't need to worry about it being initialized in constructor or not */
if(yPos!= 0)
hasJumped = true;
}
void fall(){
// do stuff
}
}
If I had multiple constructors, I still don't need to initialize legs in every constructor.
(In this case, since an IIB runs before a constructor, legs would have to be initialized either in the IIB or when the variable is declared in order for jump() to even work properly).
May not be the greatest example, but hopefully you get the idea.
+ 1
How could it be accessible to whole class, then whole concept of encapsulation will be violated.