You are on page 1of 2

EC6301 OBJECT ORIENTED PROGRAMMING AND DATA STRUCTURES

REFERENCE VARIABLES
C++ introduces a new kind of variable called reference variable.
A reference provides an alternative name for previously defined variable.
For example, if we make the variable sum a reference to the variable total, then sum and
total can be used interchangeably to represent that variable.
A reference variable is as follows:
data-type & reference-name=variable-name
example :
float total=100;
float & sum = total;
total is a float variable that has already been declared; sum is the alternative name declared to
represent the variable total. Both the variables refer to the same data object in the memory.
cout << total; and cout << sum;
Both print the value 100. The statement
total=total+10; will change the value of both total and sum to 110. Likewise the assignment
sum=0; will change the value of both variables to zero.
A reference variable must be initialized at the time of declaration.
C++ assigns additional meaning to the symbol &. Here & is not an address operator. The
notation float & means reference to float.
int n[10];
int & x=n[10];
char & a =\n

//x is alias for n[10]


// initialize reference to a literal

the variable x is an alternative to the array element n[10]. The variable a is initialized to the
newline constant. This creates a reference to the otherwise unknown location where the newline
constant \n is stored.

Page 1

EC6301 OBJECT ORIENTED PROGRAMMING AND DATA STRUCTURES

INITIALIZATION OF VARIABLES

Dynamic Initialization refers to initializing a variable at runtime.

If you give a C++ statement as shown below, it refers to static initialization, because you
are assigning a constant to the variable which can be resolved at compile time.
Int x = 5;

Whereas, the following statement is called dynamic initialization, because it cannot be


resolved at compile time.
In x = a * b;

Initializing x requires the value of a and b. So it can be resolved only during run time.

Dynamic initialization is mostly used in case of initializing C++ objects.

EXAMPLE:
#include <iostream>
using namespace std;
int main() {
double radius = 6.0, height = 6.0;
// dynamically initialize volume
double volume = 3.1416 * radius * radius * height;
cout << "Volume is " << volume;
return 0;
}

In the sample source code above, you can see that the variable "radius" and 'height" was
just initialized first and then the values of those variables were being assigned to
another variable.
It is usually used for good algorithm of a code and also for fast calculations of different
variables.
Variable 'volume' should be initialized by the values of variable "radius" and "height" .
Since the return value is not known until the program is actually executed, this is
called dynamic initialization of variable.

Page 2

You might also like