Page 56 - DCAP404 _Object Oriented Programming
P. 56
Unit 2: Beginning of OOP Language
float sum = 0; Notes
for (int i = 0; i<5; i++) //declaration
{
cin >> x;
sum = sum+x;
}
float average; //declaration
average = sum / i;
cout << average;
}
Did u know? What is the disadvantage of this style of declaration?
The only disadvantage of this style of declaration is that we cannot see at a glance all the
variables used in a scope.
2.6.3 Dynamic Initialization of Variables
One additional feature of C++ is that it permits initialization of the variables at run time. This is
referred to as dynamic initialization. Remember that, in C, a variable must be initialized using
a constant expression and the C compiler would fix the initialization code at the time of
compilation. However, in C++, a variable can be initialized at run time using expressions at the
place of declaration. For example, the following are valid initialization statements:
…..
…..
int n = strlen(string);
…..
float area = 3.14159 *rad *rad;
This means that both the declaration and initialization of a variable can be done simultaneously
at the place where the variable is used for the first time. The two statements in the following
example of the previous section
float average; // declare where it is necessary
average = sum / i;
can be combined into a single statement:
float average = sum /i; // initialize dynamically
// at run time
Dynamic initialization is extensively used in object-oriented programming. We can create exactly
the type of object needed using information that is known only at the run time.
LOVELY PROFESSIONAL UNIVERSITY 49