74 3 Numerical differentiation and interpolation
Vector v;// declare a vector of length 0
// this actually means calling the function
Vector::Vector ()
{A = NULL; length = 0;}
The constructor is the first function that is called when an object is instantiated. The variable
Ais the vector entry which defined as a private entity. Here thelength is set to zero. Note
also the way we define a method within the class by writingVector::Vector (). The general
form is< return type> name of class :: name of method(.
To give our vectorva dimensionalitynwe would write
Vector v(n);// declare a vector of length n
// means calling the function
Vector::Vector (intn)
{allocate(n);}
voidVector::allocate (intn)
{
length = n;
A =new double[n];// create n doubles in memory
}
Note that we defined a Fortran-like function for allocating memory. This is one of nice features
of C++ for Fortran programmers, one can always define a Fortran-like world if one wishes.
Moreover,the private functionallocateoperates on the private variableslengthandA. A
Vectorobject is created (dynamically) at run time, but must also bedestroyed when it is no
longer in use. The destructor specifies how to destroy the object via the tilde symbol shown
here
Vector::~Vector ()
{
deallocate();
}
// free dynamic memory:
voidVector::deallocate ()
{
delete[] A;
}
Again we have define a deallocation statement which mimicks the Fortran way of removing
an object from memory. The observant reader may also have discovered that we have sneaked
in the word ’object’. What do we mean by that? A clarification is needed. We will always refer
to a class as user defined and declared variable which encapsulates various data (of a given
type) and operations on these data. An object on the other hand is an instance of a variable
of a given type. We refer to every variable we create and use asan object of a given type. The
variableAabove is an object of typeint.
The function where we set two vectors to have the same length and have the same values
can be written as
// v and w are Vector objects
v = w;
// means calling
Vector& Vector::operator= (constVector& w)
// for setting v = w;
{
redim (w.size());// make v as long as w