You are on page 1of 1

Scientific Programming and Computer Architecture

Vector(){
size = 0;
data = NULL;
owner = 0;
}

//only constructor to allocate space for data
Vector(long int n){
size = n;
data = (double *)malloc(sizeof(double)*n);
owner = 1;
}

//*this becomes shadow of Vector v


//(copy constructor)
Vector(const Vector& v){
size = v.size;
data = v.data;
owner = 0;
}
The empty constructor and the copy constructor do not allocate space. The constructor in the middle
allocates space using malloc(), which is in cstdlib. These member functions are understood to be constructors
because they have the same name as the class. Constructors are not allowed to return anything.
Constructors are called implicitly at the point of definition of class objects. It is essential to understand when
constructors are called. Suppose we define a vector object as
Vector v;
the empty constructor is called to initialize the object v. If we define an array of vectors
Vector v[100];
the empty constructor is called for each object in the array. It is illegal to define an array of objects if the
class is not equipped with an empty constructor.
If we define a vector object as
Vector v(27)
the constructor in the middle is called. The compiler notes that the object v is being built with the single
argument 27, which is a constant of type int. The constructor that calls malloc() takes long int as an argument.
In C/C++, an int is automatically promoted to a long int if necessary.
The constructor uses malloc() to claim space for this Vector object. If we make the call

malloc(1000*1000)
the function returns a pointer to 106 bytes of memory. The pointer is of type void *.
In the usage
data = (double *)malloc(sizeof(double)*n);
void * is cast to double *. Type casts are used to convert values of one type to another type. For
example, we may say (int)1.4142 to convert the double value 1.4142 to an int (it will be truncated). The cast is
needed here because data is of type double * while malloc() returns void *.
What happens during malloc()? The short answer, which will be elaborated later, is that the function call
first goes to the C library. The C library may in turn call the operating system if it is not able to come up with the
memory by itself. The operating system typically allocates an area in virtual memory to the calling process. No
region in physical memory is set aside. Physical memory is set aside only when the process first tries to access the
memory it has claimed for itself. There is a page fault during first access, and the page fault handler sets aside
physical memory.
Suppose we need an array of Vector objects of length 100 with each vector of size 1000. The definition

https://divakarvi.github.io/bk-spca/spca.html[20-1-2019 23:44:49]

You might also like