Anda di halaman 1dari 16

Constructor:

A constructor is a special method of a class or structure in object-


oriented programming that initializes an object of that type. A
constructor is an instance method that usually has the same name as the
class, and can be used to set the values of the members of an object,
either to default or to user-defined values.

E.g.

Student() //Constructor

age = 0;

branch = “CSE”;

A constructor can be classified into following types:

1. Dummy constructor
2. Default constructor
3. Parameterized constructor
4. Copy constructor
5. Dynamic constructor
1:Dummy Constructor:

When no constructors are declared explicitly


in a C++ program, a dummy constructor is invoked which does nothing.
So, data members of a class are not initialized and contains garbage
values.

2: Default Constructor:
A constructor which does not contain any
parameters is called a default constructor or also called as no parameter
constructor. It is used to initialize the data members to some default
values. Following syntax demonstrates a default constructor:

Student() //Constructor

age = 20;

branch = “CSE”;

}
3: Parameterized Constructor:
A constructor which accepts one or
more parameters is called a parameterized constructor. Following syntax
demonstrates a parameterized constructor:

Student(int a, string b) //Constructor

age = a;

branch = b;

4: Copy Constructor:
A constructor which accepts an already
existing object through reference to copy the data member
values is called a copy constructor. As the name implies a copy
constructor is used to create a copy of an already existing object.
Following syntax demonstrates a copy constructor:

Square(int s)
{
side = s;
}
Square(Square &s)
{
side = s.side;
}

5: Dynamic Constructor: -
A constructor in which the memory for data
members is allocated dynamically is called a dynamic constructor.
Following syntax demonstrates dynamic constructor:

Student(int n) //Constructor
{
marks = new int[n];
cout<<“Enter marks for “<<n<<” subjects: “;
for(int i=0; i<n; i++)
cin>>marks[i];
}
Destructors:
Destructor" functions are the inverse of
constructor functions. They are called when objects are
destroyed (deallocated). Designate a function as a class's
destructor by preceding the class name with a tilde (~). For
example, the destructor for class String is declared: ~String().
In a /clr compilation, the destructor has a special role in
releasing managed and unmanaged resources. See Destructors
and Finalizers in Visual C++ for more information.

Delcaring destructors:
Destructors are functions with the same name as the class but
preceded by a tilde (~)
The first form of the syntax is used for destructors declared or
defined inside a class declaration; the second form is used for
destructors defined outside a class declaration.
Several rules govern the declaration of destructors. Destructors:
 Do not accept arguments.

 Cannot specify any return type (including void).

 Cannot return a value using the return statement.

 Cannot be declared as const, volatile, or static. However,

they can be invoked for the destruction of objects declared


as const, volatile, or static.
Function Overloading: -
Two or more functions having same name but different argument(s) are
known as overloaded functions.

In C++ programming, two functions can have same name if number


and/or type of arguments passed are different.

These functions having different number or type (or both) of parameters


are known as overloaded functions. For example:
int test() { }

int test(int a) { }

float test(double a) { }

int test(int a, double b) { }

Here, all 4 functions are overloaded functions because argument(s)


passed to these functions are different.

Notice that, the return type of all these 4 functions are not same.
Overloaded functions may or may not have different return type but it
should have different argument(s).

// Error code

int test(int a) { }

double test(int b){ }

The number and type of arguments passed to these two functions are
same even though the return type is different. Hence, the compiler will
throw error.
Function Overriding: -
Function overriding is a way to implement
polymorphism. Polymorphism means to have more than one behaviors
of same thing. If we have written a member function in the base class
and the same member function is also written in the derived class having
different implementation of the same member function then this is called
function overloading. It means that inheritance is required for function
overloading.
Inheritance allows software developers to derive a new class from the
existing class. The derived class inherits features of the base class
(existing class).
Suppose, both base class and derived class have a member function with
same name and arguments (number and type of arguments).
If you create an object of the derived class and call the member function
which exists in both classes (base and derived), the member function of
the derived class is invoked and the function of the base class is ignored.
This feature in C++ is known as function overriding.
Searching:
The searching problem involves determining whether a given
value is in a list. The solution to this problem is required by many
organizations and systems. A particular patient may be searched in a
database after one calls to find out if the patient of that name is in a
hospital. A search function is run when you ask for your balance in a
bank and you give your account number. Similarly, your student records
office at an educational institution will run a search algorithm to find
your student records. Search functions are widely used from shop
inventory through airline reservation to finding words in a document.
There are two methods of search. These are Linear and binary search.

Linear search:
In this method, a comparison is made with each item in the list
starting with the and continuing until the search item is found or it is
determined that the item is not in list. In the following example, an array
of values called items is passed together with a search item called
element and the array size to a function called linearsearch. The type of
the element may be one of the basic C++ types whose name was
changed to type using typedef. Here is a funtion that gives C++ code for
this algorithm:

bool linearsearch(type items[], type element, int size)


{
int position = 0;
bool found = false;

while (!found && position < size)


{
if (element == items[position])
found = true;
position++;
}
return found;
}
The problem with the linear search approach is that it always requires
going through the whole array when the search item is not in the list. It
is therefore inefficient.

Binary search:
A more efficient method of searching for an item
is binary search. This is a divide-and-conquer approach to the search
problem. Before going further into this discussion, two terms will be
introduced. These are pre-condition and post-condition.
Pre-condition: is a criteria that must hod as true before an operation is
carried out. There are some functions that need to be run only when
certain aspects of the data are satisfied. As an example, a file reading
function may require that it should be run only when the file exists. It
may may not make sense to read a file that is not there!
Post-condition is a criteria that must be true after the function has
completed running. This is used to check if a function is doing what it is
supposed to do. An example would be that when a program returns a
value of true then the item being searched must really be in the list.

The binary search method has a pre-condition. The array must be in


sorted order before the search starts. If the array is not sorted, the
function may report an item as not found when it is actually in the array.
Below is the binary search algorithm.

1. Compare the search item with the item in the middle of the list
2. If item in middle of list is equal to search item then
report that item is found and stop
3. else determine if search item is smaller or larger than item in the
middle
a. If search item is smaller that item in the middle
make middle to be middle of smaller items
b. else
make middle to be middle of larger items
4. if list cannot be subdivide further
report that item not found and stop
5. else
go to 1

The above algorithm can be written in C++. There is need to


maintain values in variables that point to the bottom, middle,
and the top of the array. Below is the C++ code:

bool binarysearch(type items[], type element, int size)


{
bool found = false;
int bottom, middle, top;

bottom = 0;
top = size - 1;
while (!found && bottom <= top)
{
middle = (bottom + top)/2;

if (items[middle] == element)
found = true;
else
if (items[middle] > element)
top = middle - 1;
else
bottom = middle + 1;
}

return found;
}
Sorting:
There are several reasons why data in a list such as an array needs to be
sorted. Some of the reasons are as follows:

 To produce ordered output. An example of ordered output is a


telephone directory where names are in alphabetical order. Another
example is a schedule of events that are ordered by date. A bank
statement also sorts items by date. Some listings may prefer
descending order of listing records. Examples of such listings are
student scores on a test where the highest is listed first. Similarly a
sports how they stand table usually lists the team with the highest
points first.
 To prepare data for a subsequent operation or function of computer
processing that requires sorted data. An example of a function that
requires sorted data is binary search. Given an array of unsorted
data, it is necessary to first sort the data in the array before passing
the array to binary search.

Sorting is so important that many applications have in-built sort routines.


Packages such as Microsoft Excel enable the user to sort cells by a
specified criterion. Even programming language have built-in sort
functions that the programmer can just call. C++ is no exception as it has
the qsort function found in the cstdlib library. However, it is important
to understand how sorting algorithms work. There are many sorting
approaches including selection sort, insertion sort, bubble sort, shell sort,
quick sort, merge sort, heap sort, and binary search tree sort. In these
notes only the selection sort details are presented.

Selection sort algorithm:


Assume that elements are to be sorted in ascending order. Selection sort
works by going through the list several times. Each time the smallest
item is identified. The item identified as the smallest is exchanged with
the item that is at a position matching the loop number. Here is the
algorithm.
SELECTION SORT ALGORITHM:
1. Get a list of items and do the following:
make first position the start of sublist make the first
position the position of the smallest.
2. Go through the list. Anytime an item smaller than the one assumed
to be smallest is encountered, change the smallest item to the new
one and remember its position as the new position of the smallest.
3. Exchange items in the start of sublist and position of smallest
4. Add 1 to the start of sublist and make position of smallest the
new start of sublist
5. Go to step 2 above
6. Selection sort C++ function

In the example below, a list of items of a basic C++ type and


the number of items are passed to the function. The name of
the type may be given by using typedef. Below is the C++
version of the algorithm given above.

// This function implements the selection sort algorithm


// Pre-condition: a non-empty list of items
// Post-condition: items sorted in ascending order
void SelectionSort(type items[], int size)
{
int posOfSmallest;
type temp;

for (int startPos = 0; startPos < size; startPos++) //Changing


start of sublist
{
// Assume start of sublist contains smallest item in sublist
posOfSmallest = startPos;
for (int searchIndex = startPos+1; searchIndex < size;
searchIndex++)
// Going through array looking for the real smallest item
in sublist
if (items[searchIndex] < items[posOfSmallest])
posOfSmallest = searchIndex; // Changing position
of smallest
// The following three statements exchange elements at
// start of sublist and position of smallest.
temp = items[posOfSmallest];
items[posOfSmallest] = items[startPos];
items[startPos] = temp;
}
}

Multi-dimensional:
A multidimensional array has more than one sizes specified at
declaration. Here is an example:

const int ROWS = 5;


const int COLS = 5;

int TwoDimIntArray[ROWS][COLS];
This declaration can be thought of as a two dimensional table of 5 rows
and 5 columns as shown below:
[ ][ ][ ][ ][ ]
[ ][ ][ ][ ][ ]
[ ][ ][ ][ ][ ]
[ ][ ][ ][ ][ ]
[ ][ ][ ][ ][ ]
To index such an array, there is need to use two indexes as follows:
TwoDimIntArray[2][3] = 1243;
This will result in a memory snapshot that looks as follows:

[ ][ ][ ][ ][ ]
[ ][ ][ ][ ][ ]
[ ][ ][ ][1243][ ]
[ ][ ][ ][ ][ ]
[ ][ ][ ][ ][ ]
The program can display to the screen the value stored in row 2 column
3 using an output statement that looks as follows:

cout << TwoDimIntArray[2][3] << endl;

Analysis of algorithms:
Algorithm running times are approximated by writing a
formula that depends on the number of data values the algorithm will
process. Usually, this can be done by letting a variable such
as n represent the number of data values and then counting how many
times the statement that is repeated most will execute in relation to the
variable n.

Anda mungkin juga menyukai