II PUC Computer Science Textbook 191-480
II PUC Computer Science Textbook 191-480
5.9 FUNCTIONS
If the programs are complex and lengthy, they can be modularized into
subprograms. The subprograms are called as functions. The subprograms can be
developed independently, compiled and tested. They can be reused in other
programs also.
A function is a named group of statements developed to solve a sub-problem
and returns always a value to other functions when it is called.
Types of functions
There are two types of functions:
i. Library functions
ii. User-defined functions.
i. Library functions
A standard library is a collection of pre-defined functions and other
programming elements which are accessed through header files.
Header files are the files containing standard functions that our programs
may use. This chapter contains the information about some header files of C++
standard library and some functions of it. The header files should be written within
angled brackets and its functions are included into our programs by #include
directive.
User-defined functions
We can create our own functions or sub-programs to solve our problem.
Such functions are normally referred to as user defined functions.
A user-defined function is a complete and independent program, which
can be used (or invoked) by the main program or by the other sub-programs. The
user-defined functions are written to perform definite calculations, after performing
their task they send back the result to the calling program or sub-program.
Different header files
As said earlier, header files are the files containing standard functions
that our programs may use. C++ contains many header files and is listed below.
stdio.h
This header file contains functions and macros to perform standard I/O
operations. When we include the header file iostream.h, the header file stdio.h is
automatically included into our program.
string.h
This header file declares functions to manipulate strings.
stdlib.h
This header file is used to declare conversion routines, search/sort routines
and other miscellaneous things.
Review of C++173 173
iostream.h
This header file contains C++ streams and i/o routines.
iomanip.h
This header file contains functions and macros for I/O manipulators for
creating parameterized manipulations.
math.h
This header file declares prototypes for the mathematical functions and
error handlers. The functions are used to perform mathematical calculations.
Mathematical library functions
C++ provides many mathematical functions. These functions can be used
in mathematical expressions and statements. The various functions are ceil(), exp(),
fabs(), floor(), log(), pow() etc.
Character and string functions
A character is any single character enclosed within single quotes. Some
functions accept a character as argument. The argument is processed as an int by
using its ASCII code. To use these functions, the header file ctype.h should be
included.
Inputting single character
We can input a character using the function get( ).
char ch; char ch;
cin = get(ch); OR ch = cin.get( );
Outputting single character
cout.put(ch);
put() function is used to display single character.
The general form is
Example : char ch; ch = cin.get(); cout.put(ch);
String functions
A string is sequence of characters enclosed within double quotes. Strings
are manipulated as one-dimensional array of characters and terminated by null
(‘\0’) character. C++ provides many functions to manipulate strings. To use these
functions, the header file string.h should be included.
char string-name[size];
Declaring a string variable
The general form to declare a string is:
Ø string-name is the name of the string variable
174 Review of C++
Ø Size is the number of characters in the string. The size helps the compiler
to allocate required number of memory locations to store the string.
Example : char st[50];
Initializing a string
Like other variables, strings can also be initialized when they are declared.
Example : char s[10] = “Karnataka”;
There are only 9 characters in the string. The null character (‘\0’) is
automatically appended to the end of the string.
Inputting a string
C++ provides the function getline() to read a string.
cin.getline(string, size);
Example cin.getline(st, 25);
Outputting a string
C++ provides the function write() to output a string.
cout.write(string, size);
Example : cout.write(st, 25);
Some string manipulation functions are given below:
strlen() function
This function returns the length of the string. i.e., the number of characters
present in the string, excluding the null character.
The general form is variable = strlen(string);
Example 12.9: l = strlen(“Empress”); Returns 7.
strcat() function
This function is used to concatenate two strings. The process of combining
two strings to form a string is called as concatenation.
strcpy() function
A string cannot be copied to another string by using assignment statement.
The function strcpy() is used to copy a string into another string.
strcmp() function
This function is used to alphabetically compare a string with another string.
This function is case-sensitive. i.e., it treats the uppercase letters and lowercase
letters as different.
strcmpi() function
Review of C++175 175
This function is used to alphabetically compare a string with another string.
This function is not case-sensitive. i.e., it treats the uppercase letters and lowercase
letters as same.
strrev() function
This function is used to reverse the characters in a string.
5.10 USER DEFINED FUNCTIONS
Definition
User-defined function is a function defined by the user to solve his/her
problem. Such a function can be called (or invoked) from anywhere and any number
of times in the program.
Function definition or structure of user-defined function
Function-header
Any user-defined function has the following structure.
return-type-specifier function-name(argument-list with declaration)
{
Local-variable-declarations;
Executable-statement-1;
Body of the function
Executable-statement-2;
………..
Executable-statement-n;
return(expression);
}
Ø Return-type-specifier is the data type of the value return by the function
to anther function when it is called. The return-type-specifier can be char, int, float
or void. The data type void is used when the function return no value to the calling
function.
Ø Function-name is the name of the function. It is an identifier to identify
the particular function in a program.
Ø Argument-list with declaration is the list of arguments or parameters or
variables with their declaration. Each argument should be declared separately.
Each declaration should be separated by comma. The list should be enclosed within
parenthesis.
Ø The complete line is called the function header. Note that there is no
semicolon at the end.
Ø Local-variable declaration is the declaration of the variables that are used
within the function. Since these variables are local to the function, these variables
are called as local variables.
Ø Executable-statements are the statements that perform the necessary
operations to solve the problem. If the function is returning a value, a return
176 Review of C++
Types of Functions :
There are 5 types of functions.
i. Functions with no arguments and no return values
ii. Functions with arguments and with no return values
iii. Functions with no arguments and with return values
iv. Functions with arguments and with return values
v. Recursive functions
Functions with no arguments and with no return values
In this method, the function simply performs an independent task. The
function does not receive or send any arguments.
Example : void natural()
{
for(int i=1; i <= 10; i++)
cout<<setw(4)<<i;
}
Functions with arguments and with no return values
In this method, the function receives some arguments and does not return
any value.
Example : void average(int x, int y, int z)
{
float sum, avg;
sum = a + b + c;
avg = sum/3.0;
cout<<“Average = “avg<<endl;
}
Functions with no arguments and with return values
In this method, the function receives no arguments but return a value.
Example : int greatest()
{
if(a>b)
return(a);
return(b);
}
Functions with arguments and with return values
In this method, the function receives some arguments and returns a value.
Example : float interest(float p, float t, float r)
{
si = (p * t * r)/100;
return(si);
}
Review of C++179 179
Recursive functions
Recursive function is a function that calls itself. The process of calling a
function by itself is called as recursion.
Recursive functions must have one or more terminating conditions to
terminate recursion. Otherwise, recursion will become infinite.
Passing default arguments to functions
In C++, to call a function we need not pass all the values for the arguments
to a function from the calling function. It allows us to assign default values to the
formal arguments.
Example : Consider the prototype
float interest (float amt, int time, float rate = 0.15);
0.15 is the default value provided to the argument rate.
The function call statement can be as follows:
si = interest( 5000,5 ); // third argument is missing
Default values should be assigned only in the function prototype. It should not be
repeated in the function definition.
Passing constant arguments
In C++, we can declare some arguments as constants. The compiler cannot
modify the arguments marked as constants.
Example : int strlen(const char *p);
int total( constint x, const int y);
Pass by value or Call by value
A function can be called by passing arguments from the calling function
into the called function. Thus the data is transferred through argument list.
Pass by reference or call by reference
We can pass parameters to the function by using reference variables. When
we pass arguments by reference, the formal arguments in the called function become
the aliases to the actual arguments of the calling function. i.e., the called function
is actually uses the original data with a different name.
Passing arrays to functions
To pass an array to a function, we just pass the name of the array to the
function. i.e., we are referring the address of the first element of the array. Using
this address, the function can access all the elements of the array.
Passing structures to functions
We can pass structures to functions as we pass other arguments. Structures
are passed to functions in pass-by-value method. i.e., the function works with copy
of the structures. The function can also return a structure after processing it.
180 Review of C++
Whenever we pass the address of the structure to the function, we should include
the address-of (&) operator.
5.11 Structures
A structure is a collection of simple variables. The variables in a structure can be of
same or different types: Some can be int, some can be float and so on. The data
items in a structure are called the members of the structure.
Defining a structure
The process of defining a structure is equivalent to defining your own data
type.
struct structure-name
{
datatype member-name-1;
datatype member-name-2;
……………
datatype member-name-n;
};
Example: A structure definition to hold employee information.
struct employee
{
int idno;
char name[15];
char designation[10];
float salary;
};
Basic concepts of OOP 181
Chapter 6
BASIC CONCEPTS OF OOP
Objectives:
6.1 Introduction
Object oriented programming is the principle of design and development of
programs using modular approach. Object oriented programming approach
provides advantages in creation and development of software for real life
applications. The advantage is that small modules of program can be developed
in shorter span of time and these modules can be shared by a number of
applications. The basic element of object oriented programming is the data. The
programs are built by combining data and functions that operate on the data. In
this chapter we learn about the basic concepts, advantages and terminologies
used in Object oriented programming. Some of the object oriented programming
languages are C ++, Java, C # and so on.
The object oriented programming methods use data as the main element in
the program. The data is tied to the function that operates on the data and the
other functions cannot modify the data tied to a given function. Thus in object
oriented programming, a problem is decomposed into a number of components
called objects. An object is a collection of set of data known as member data and
the functions that operate on these data a known as member functions or
Methods. The member data are encapsulated in an object and then can be
accessed or modified only by the member functions. An object can be accessed
only if permitted by other member functions. Various objects of a program can
interact with each other by sending messages.
Object oriented programming methods modularize a program by creating
memory area for data and member functions (methods) together as a single
entity. All objects are created according to the specifications of the entity defined.
Object is the basic unit of OOP. To design OO Model, first a set of classes are
defined. A class is a Template from which objects are created. The Template of a
class specifies the data , member functions and their attributes.
Basic concepts of OOP 183
6.2.1 Objects
Objects are basic building blocks for designing programs. An object may
represent a person, place or a table of data. An object is a collection of data
members and associated member functions. Each object is identified by a unique
name. Every object must be a member of a particular class.
Ex: Apple, orange, mango are the objects of class fruit.
Objects take up space in memory and have address associated with them.
For example, structure variable in a C program.
At the time of execution of a program, the objects interact by sending messages
to one another. The objects can interact with one another without having to
know the details of data or functions within an object.
Objects
6.2.2 Classes
The objects can contain data and code to manipulate the data. The objects
can be made user defined data types with the help of a class. Therefore objects
184 Basic concepts of OOP
6.2.5 Inheritance
In OOP, the concept of inheritance provides the
idea of reusability. This means that we can add
additional features to an existing class without
modifying it. Thus the process of forming a new
class from an existing class is known as
Inheritance. The objects of one class acquire the
properties of another class through inheritance.
The existing class is known as base class. The new class is known as derived
class.
The derived class shares some of the properties of the base class. Therefore
a code from a base class can be reused by a derived class. In addition to this the
new class may combine features from two different base classes too.
Basic concepts of OOP 185
In single inheritance, each subclass has only one superclass. In Multiple
inheritance, each subclass has more than one super class.
6.2.6 Overloading
Overloading allows objects to have different meaning depending upon
context. There are 2 types of overloading namely
1. Operator overloading
2. Function overloading
When an existing operator operates on new data type, it is called operator
overloading.
Function overloading means two or more functions have same name ,but
differ in the number of arguments or data type of arguments. Therefore it is said
that (function name) is overloaded. Function overloading therefore is the pro-
cess of defining same function name to carry out similar types of activities with
various data items.
6.2.7 Polymorphism
Polymorphism is a feature of object oriented programming where a function
can take multiple forms based on the type of arguments, number of arguments
and data type of return value.
The ability of an operator and function to take multiple forms is known as
polymorphism.
Example 1.2: Consider the addition operation. In addition of 2 numbers
the result is the sum of 2 numbers.
In addition of 2 strings the operation is string concatenation. When an
operator behaves differently based on operands, then it is said that operator is
overloaded. Similarly when same function is used for multiple tasks in the same
program by changing argument type and number, it is known as function
overloading.
6.2.8 Dynamic Binding
Binding is the process of connecting one program to another. Dynamic
binding means code associated with a procedure call is known only at the time
of program execution routine.
6.2.9 Message Passing
In OOP, processing is done by sending messages to objects. A message for
an object is request for execution of procedure. The request will involve a
procedure (function) in the receiving object that generates desired results.
Message passing involves specifying the name of object, the name of the function
(message) and the information to be sent.
186 Basic concepts of OOP
Chapter 7
Classes and objects
Objectives:
7.1 Introduction
In the previous chapter we have learnt the fundamentals units of an object
oriented programming. In this chapter let us understand the basic units of data
representation for development of any object oriented programming namely
classes and objects.
Real world objects can be represented as data variables in computer domain.
Data variables are identified as account numbers, balance_payment,
Employee_code and so on. When these real world objects are represented as
data in computers, they can also be manipulated or processed by using functions
in C++. For instance account information of a customer in a bank can be updated,
balance_payment can be computed and so on. To combine the data variables
(objects) along with appropriate functions for manipulation of these objects, the
concept of classes were introduced in object oriented programming.
The elementary concept of object oriented programming begins with the
use of classes and objects. A class is a very powerful keyword in C++. A class
declaration defines new user-defined data types that link data and the code that
manipulates the data. In other words, a class combines data elements and
functions (operations) into a single entity.
Variables Objects
User-defined data types Classes
Structure members Instance variables
Functions Methods
Function call Message passing
The data elements in a class are called member data and the functions in
a class are called member functions. This chapter explains classes, objects,
member functions, data hiding, abstraction, encapsulation and how these
features are implemented using classes (further chapters provide details of single
inheritance, multiple inheritances, insight to polymorphism and other functions).
Classes and objects 191
In the above example, class name account is a new type identifier that is
used to declare instance of that class type. The class account contains four
member data and two methods or member functions. Both of these member
data are private by default, while both member functions are public by default.
The functions get_data( ) and put_data( ) are used to write instructions to
perform operations on member data. These two functions only can provide access
to get member data from outside the class. Therefore, the data cannot be accessed
by any other function that is not a member of the class account.
#include<iostream.h>
#include<conio.h>
class Test
{
private:
int a,b;
public:
void getnum()
{
cout<<"Enter Numbers for Addition: ";
cin>>a>>b;
}
void show_data()
{
cout<<"Addition of two numbers: "<<(a+b);
}
};
Classes and objects 193
int main()
{
clrscr();
Test a1;
a1.getnum();
a1.show_data();
getch();
return 0;
}
int get_height ( )
{
return height ;
}
};
int main()
{
box object;
object.length = 10;
object.width = 20;
object.set _height ( 30); // private variable can be accessed
return 0; only through its public method
}
Thus keyword public identifies both class data and functions that constitute
the public interface for the class. In the above program data member width is a
public variable. set_height() and get_height() are member functions. The private
variable height can be accessed only through the member functions of the class.
Thus keyword public identifies both class data and functions that constitute
the public interface for the class.
7.3.3 Protected
The members which are declared using protected can be accessed only by
the member functions, friends of the class and also by the member functions
derived from this class. The members cannot be accessed from outside. The
protected access specifier is therefore similar to private specifier. The difference
is discussed in detail in further chapters.
7.4. Members of the class
The members of a class can be data or functions. Private and protected
members of a class can be accessed only through the member functions of that
class. No function outside a class can include statements to access data directly.
The public data members of objects of a class can be accessed using direct
member access operator (.)
The syntax for accessing class member is
class-object. member-data
class-object.member-function(arguments);
Example 7.4: class rectangle
{
int l;
int b;
public:
Classes and objects 195
void get_data();
void compute_area();
void display();
};
int main()
{
rectangle rl;
rl.get _data();
rl.compute_data();
r1.display();
return 0;
}
In the above example l and b are data members of class rectangle and
get_data(), compute_data() and display() are member functions. r1 is a class
variable that invokes the member functions.
Program 7.2. Program to show the use of access specifiers with classes and
objects
#include<iostream.h>
#include<conio.h>
class data
{
private:
int day;
int month;
int year;
public:
void date(int dd,int mm,int yy)
{
day = dd;
month = mm;
year = yy;
cout<<"\t"<<day<<"\t"<<month<<"\t"<<year<<endl;
}
};
int main()
{
clrscr();
data date1,date2;
date1.date(7,12,2014);
date2.date(8,12,2014);
date1.date(12,12,2014);
getch();
196 Classes and objects
return 0;
}
In the above program day, month and year are private members and date
is a public function. The output of the above program is as follows.
member function has an ‘identity label’ in the header. This label tells the compiler
which class the function belongs to. The scope of the member function is limited
to the class mentioned in the header. Scope resolution operator :: is used to
define the member function.
Syntax: For member function outside a class
return_type classname :: memberfunction(arg1, arg2, …, argn)
{
function body;
}
The member functions have following characteristics:
Type and number of arguments in member function must be same as
types and number of data declared in class definition.
The symbol :: is known as scope resolution operator. Usage of :: along
with class name is the header of function definition. The scope resolution
operator identifies the function as a member of particular class.
Several classes can use same function name. Membership label will resolve
their scope.
Member function can access private data of a class. A non-member function
cannot.
Example 7.6: The following program segment shows how a member function
is defined outside class.
class operation
{
private :
int a;
int b;
public :
int sum();
int product();
};
int operation::sum()
{
return (a+b) ;
}
In the above example sum() and product() are member functions defined
outside class operation. The use of scope resolution operator implies that
these member functions are defined outside the class.
Program 7.3 To use classes using member functions inside and outside
class definition.
# include<iostream.h>
class item // class declaration
{
int number; // private by default
float cost;
public :
void getdata(int a, float b);
void putdata(void) // function defined here
{
cout <<"Number: "<< number << endl;
cout << "Cost: "<< cost << endl;
}
};
// member function outside class definition
void item :: getdata(int a, float b)
{
number = a;
cost = b;
}
// main program
int main()
{
item x; // create object x
x.getdata(250, 10.5);
x.putdata();
return 0;
}
In the above program one member functions putdata() is defined inside
class definition and the other member function getdata() is defined outside
class definition. Here is the output of program.
Number : 250
Cost : 10.5
7.6. Defining objects of a class
When a class is defined, it specifies the type information the objects of the
class store. Once the class is defined an object is created from that class. The
Classes and objects 199
objects of a class are declared in the same manner like any other variable
declaration.
Syntax : class user_defined_name
{
private: //Members
public: // Methods
};
User_defined_name object1, object2, … ;
Example 7.6: class num
{
private:
int x;
int y;
public:
int sum(int p, int q);
int diff(int p, int q);
};
void main()
{
num s1,s2;
s1.sum(200,300);
s2.diff(600,500);
}
Note that an object is an instance of a class template.
Example 7.6 A class to create studentname, rollno, sex, age.
class student
{
int rollno;
char name[20];
char gender;
int age;
public:
void get_data();
void display_data();
};
student obj1, obj2; //Obj1, obj2 are objects of class student
7.7 Arrays as members of classes
So far we have considered primary data values as member of class. Just
like arrays within structures, it is possible to use arrays as member data of class
type.
200 Classes and objects
Name Age
supervisor[0]
supervisor[1]
supervisor[2]
Storage of data items in an object array
#include<iostream.h>
#include<conio.h>
class data
{
int rollno, maths, science;
public:
int avg();
void getdata();
void putdata();
};
void data::getdata()
{
cout<<"Enter rollno: ";
cin>>rollno;
cout<<"Enter maths marks: ";
cin>>maths;
cout<<"Enter science marks: ";
cin>>science;
putdata();
}
int data::avg()
{
int a;
a=(maths+science)/2;
return a;
}
void data::putdata()
{
cout<<"Average = "<<avg()<<endl;
}
int main()
{
202 Classes and objects
clrscr();
data stud[3];
for(int i=0;i<3;i++)
stud[i].getdata();
return 0;
}
Enter rollno: 23
Enter maths marks: 56
Enter science marks: 78
Average = 67
Enter rollno: 24
Enter maths marks: 56
Enter science marks: 77
Average = 66
Enter rollno: 12
Enter maths marks: 44
Enter science marks: 89
Average = 66
In the above program stud is an array of objects, data is a class with member
functions getdata() and putdata() defined outside the class definition.
7.9. Objects as function arguments
A function can receive an object as a function argument. This is similar to
any other data type being sent as function argument. An object can be passed to
a function in two ways:
Copy of entire object is passed to function (pass-by-value).
Only address of the object is transferred to the function (pass-by-reference).
In pass by value, a copy of the object is passed to the function. The function
creates its own copy of the object and uses it. Therefore changes made to the
object inside the function do not affect the original object.
In pass by reference, when an address of an object is passed to the function,
the function directly works on the original object used in function call. This
means changes made to the object inside the function will reflect in the original
object, because the function is making changes in the original object itself.
Pass-by-reference is more efficient, since it require only to pass the address
of the object and not the entire object.
Classes and objects 203
#include<iostream.h>
#include<conio.h>
class currency
{
int rupee, paise;
int total;
public:
void get_value(int r, int p);
void display(void);
};
void currency::get_value(int r, int p)
{
rupee = r;
paise = p;
total = r*100 + p;
}
void currency::display(void)
{
cout<<rupee<<" Rupees "<<" and "<<paise<<" paise"<<endl;
cout<<"Converted value: "<<total<<" paise";
}
int main()
{
currency c;
c.get_value(5, 75);
c.display();
}
#include <iostream.h>
#include<conio.h>
class rup
{
private:
int n1,n2;
public:
rup():n1(1),n2(1)
204 Classes and objects
{
}
void get()
{
cout<<“enter first number”;
cin>>n1;
cout<<“enter second number”;
cin>>n2;
}
void print()
{
cout<<“product=”<<n1<<endl;
cout<<“product2=”<<n2<<endl;
}
void multi(rup r1,rup r2)
{
n1=r1.n1*r1.n2;
n2=r2.n1*r2.n2;
}
};
int main ()
{
rup r1,r2,r3;
clrscr();
r1.get();
r2.get();
r3.multi(r1,r2);
r3.print();
getch();
return 0;
}
7.10. Differences between structure and class:
In C++, a structure is a class defined with the keyword struct. Its members
and base classes are public by default. A class is defined with the class keyword
Points to remember:
A class is a user defined data that contains data members and objects
An object is an instance of a class.
Members: There are two types of members in a class. They are data member
and member functions.
Data members are different data variables similar to structure members.
Data members may be declared in a class as private, public or protected.
Classes and objects 205
1. What is a class?
2. What is an object?
3. What are the two types of members referenced in a class?
4. What are data members?
5. What is a member function?
6. Mention the access specifiers used with a class
7. Is it possible to access data outside a class?
8. Which type of data members are accessible outside a class?
9. Which access specifier is implicitly used in a class?
10. Define the term public access
11. Mention the operator used to access members of a class
12. What is the significance of scope resolution operator (::)?
13. How are objects of a class declared? Give an example
14. What is meant by an array of objects?
15. Write an example to show how objects can be used as function
arguments?
Two/Three mark questions
1. Write the differences between class definition and class declaration.
2. Write the syntax and example for class definition.
3. Write the syntax and example for class declaration.
4. What is the significance of using access specifiers? Mention different
access specifiers.
5. Discuss private access specifier with an example.
206 Classes and objects
Objects:
Ø Need for function overloading
Ø Concept of polymorphism
Ø Application of function overloading through simple examples
Ø Concept of inline functions
Ø Use friend functions
208 Function overloading
8.1 Introduction
In the previous chapter, we have learnt about classes and objects. The
application of classes with data members and member functions is the principle
feature of object oriented programming to develop and simplify programming
methods. Another feature to help for easier programming is polymorphism. The
definition of polymorphism has appeared in chapter 6. Let us recall the definition
once again. Polymorphism refers to “one name having many forms, different
behavior of an instance of an object depending on situations”.
C++ implements polymorphism through function overloading and operator
overloading. The function overloading allows the user to create new abstract
data types. In this chapter we learn about the need for function overloading,
definition and declaration of function overloading and some examples. The
discussion is limited to design of a set of functions that perform essentially the
same thing, but with a different argument list. The selection of overloaded function
depends on matching arguments at the time of compilation. The study in this
chapter is also extended to inline and friend functions.
8.2 Need for function overloading
Function overloading means two or more functions have same name, but
differ in the number of arguments or data type of arguments. Therefore it is said
that (function name) is overloaded. Function overloading therefore is the process
of defining same function name to carry out similar types of activities with various
data items. The advantages of function overloading are:
When different functions are created for different operations, then user
has to call respective function depending on the situation. Instead, for
different situations if the same function is called with different arguments
using function overloading, then the compiler automatically decides about
the appropriate function by comparing the argument types used in the
call to the function and calls the required function. Thus the code is
executed faster.
It is easier to understand the flow of information and debug.
Code maintenance is easy.
Easier interface between programs and real world objects.
8.3 Definition and declaration of overloaded functions
The main factor in function overloading is a function’s argument list. C++
can distinguish overloaded functions by the number and type of arguments. If
there are two functions having same name and different types of arguments or
different number of arguments, then function overloading is invoked automatically
by the compiler. Function Overloading is also known as Compile time
polymorphism.
Function overloading 209
Example 8.1: int sum(int a, int b);
float sum(float p, float q);
The function sum() that takes two integer arguments is different from the
function sum() that takes two float arguments. This is function overloading.
To overload a function, each overloaded function must be declared and
defined separately.
Example 8.2: int product(int p, int q, int r);
float product(float x,float y, float z);
int product(int p, int q, int r)
{
cout<<“product=”<<p*q*r<<endl;
}
float product(float x,float y,float z)
{
cout<<product=”<<x*x*y*y*z*z<<endl;
}
In this example the function product() is overloaded two times. First time
with three integer values and integer as return value, second time with three
float values and return type being a float. The compiler automatically chooses
the right type of function depending on the number of arguments.
8.4 Restrictions on overloaded functions
Ø Each function in a set of overloaded functions must have different argument
list.
Ø If typedef is used for naming functions, then the function is not considered
as different type.
8.4.1 Calling overloaded functions
The following programming example shows how overloaded functions can
be called.
Program 8.1: To compute volume of cone, cube and cylinder using overloaded
functions.
#include<iostream.h>
#include<conio.h>
class funoverload
{
public:
int volume(int a) // Volume of Cube
{
return a*a*a;
}
210 Function overloading
Square of 5 = 25
Square of 10 = 100
In the above example square() is an inline function that finds the square
of a number.
Note: The inline function may not work some times for one of the following
reasons:
The inline function definition is too long or too complicated.
The inline function is recursive.
The inline function has looping constructs
The inline function has a switch or goto.
8.5.2 friend functions
We have seen that private and protected members of a class cannot be
accessed from outside the class in which they are declared. In other words non-
member function does not have access to the private data members of a class.
But there could be a situation where two classes must share a common function.
C++ allows the common function to be shared between the two classes by making
the common function as a friend to both the classes, thereby allowing the function
to have access to the private data of both of these classes.
A friend function is a non-member function that is a friend of a class. The
friend function is declared within a class with the prefix friend. But it should be
defined outside the class like a normal function without the prefix friend. It can
access public data members like non-member functions.
Syntax: class class_name
{
public:
friend void function1(void);
friend returntype_specifer function_name(arguments);
};
Example 8.3: class base
{
int val1, val2;
public:
void getdata()
{
cout<<“Enter two values:”;
cin>>val1>>val2;
}
};
Function overloading 213
friend float mean(base ob);
float mean(base ob)
{
return float(ob.val1+ob.val2)/2;
}
In the above example mean() is declared as friend function that computes
mean value of two numbers that are input using getdata() function.
A friend function although not a member function, has full access right to
the private and protected members of the class.
A friend function cannot be called using the object of that class. It can be
invoked like any normal function.
They are normal external functions that are given special access privileges.
It cannot access the member variables directly and has to use an object
name.membername (Here, is a membership operator).
The function is declared with keyword friend. But while defining friend
function it does not use either keyword friend or :: operator.
#include <iostream.h>
class myclass
{
private:
int a,b;
public:
void set_val(int i, int j);
friend int add(myclass obj);
};
void myclass::set_val(int i,int j)
{
a = i;
b = j;
}
int add(myclass obj)
{
return (obj.a+obj.b);
}
214 Function overloading
int main()
{
myclass object;
object.set_val(34, 56);
cout << “Sum of 34 and 56 is “<<add(object)<<endl;
return 0;
}
Sum of 34 and 56 is 90
Chapter 9
CONSTRUCTORS AND DESTRUCTORS
Objectives:
Need for use of constructors
The above program shows the use of default constructor student that
initializes the members automatically as soon as they are created.
Disadvantages of default constructor:
When many objects of the same class are created, all objects are initialized
to same set of values by default constructor
It is not possible to initialize different objects with different initial values
using default constructor.
9.3.2 Parameterized Constructors:
A constructor that takes one or more arguments is called parameterized
constructor. Using this constructor, it is possible to initialize different objects
with different values.
Parameterized constructors are also invoked automatically, whenever
objects with arguments are created. The parameters are used to initialize the
object.
Features of parameterized constructors:
The parameterized constructors can be overloaded.
For an object created with one argument, constructor with only one
argument is invoked and executed.
The parameterized constructor can have default arguments and default
values.
Invoking constructors
A constructor is automatically invoked by C++ compiler with an object
declaration. The constructors can be invoked through the following methods:
222 Constructors and Destructors
1. Explicit call
2. Implicit call
3. Initialization at the time of declaration with = operator
Explicit call
In explicit call, declaration of an object is followed by assignment operator,
constructor name and argument list enclosed in parenthesis.
Program 9.4: To use parameterized constructor through explicit call
#include<iostream.h>
class num
{
private:
int a,b;
public:
num(int p, int q) {a = p,b = q;}
void display()
{
cout<<"a = "<<a<<" and b = "<<b<<endl;
}
};
void main()
{
num obj1=num(10,20);
num obj2=num(40,50);
cout<<"First construction: ";obj1.display();
cout<<"Second construction: ";obj2.display();
}
In the above program code the objects obj1 and obj2 are called explicitly
by using parameterized constructor.
Implicit call
An Implicit call means the declaration of the object is followed by argument
list enclosed in parentheses.
Program 9.5: Program to intialise the data members using implicit declaration
#include<iostream.h>
class num
{
private:
Constructors and Destructors
223
int a,b;
public:
num(int m, int n)
{ a = m, b = n; }
void display()
{
cout<<"a= "<<a<<" b= "<<b<<endl;
}
};
void main()
{
num obj1(10,20);
num obj2(40,50);
obj1.display();
obj2.display();
}
a=10 b= 20
a=40 b=50
Note that:
1. One parameterized constructor num(int m, int n) is defined inside the
class.
2. For each object, different values are passed from function main(). Therefore
different objects can be initialized to different values.
Initialization of objects during declaration with assignment operator
This method is used for the constructor with exactly one argument. In this
method declaration is followed by assignment operator and value to be initialized.
Program 9.6: To initialize objects using assignment operator
#include<iostream.h>
class num
{
private:
int a;
public:
num(int m) { a = m; }
void display()
{
cout<<a<<endl;
}
};
void main()
{
224 Constructors and Destructors
num obj1=100;
num obj2=200;
cout<<"Object1 = ";obj1.display();
cout<<"Object2 = ";obj2.display();
}
Object1 = 100
Object2 = 200
In the above example, the constructors obj1 and obj2 are initialized using
= operator.
Note that
1. This method is applicable only to the constructors that have exactly one
parameter.
2. If a class contains at least one parameterized constructor, then necessary
arguments have to be passed to the constructor in the declaration itself.
3. If user does not want to pass arguments, then default constructor must be
created in the class.
Example 9.1: num obj1(10,20);
num obj2; //error
num() { } //This default constructor must be included in
//class num to avoid errors
The above example shows that it is necessary to use a default constructor
num() to avoid error during the declaration of num obj2;
9.3.3 Copy constructor
Copy constructor is a parameterized constructor using which one object
can be copied to another object. Copy constructors are used in the following
situations.
To initialize an object with the values of already existing objects.
When objects must be returned as function values
To state objects as by value parameters of a function.
Copy constructor can accept a single argument of reference to same class
type. The argument must be passed as a constant reference type.
Syntax: classname :: classname(classname &ptr)
Example 9.2: x::x(x &ptr)
Constructors and Destructors
225
Here, x is a class name and ptr is a pointer to a class object x.
If there is more than one argument present in the copy constructor, it
must contain default arguments.
Note that:
1. Copy constructor is not invoked explicitly.
2. Copy constructor is invoked automatically when a new object is created
and equated to an already existing object in the declaration statement
itself.
Example 9.3: x a1; //default constructor
x a2 = a1; //copy constructor
a1.display();
The above example shows the use of copy constructor to create a new
object a2 using existing object a1.
3. When a new object is declared and existing object is passed as a parameter
to it in the declaration, then also copy constructor is invoked.
Example 9.4: x a1(100,200);//parameterized constructor
x a2(a1); //copy constructor is invoked for
//object a2 with a1 as parameter
4. When an object is passed to a function using pass-by-value, copy constructor
is automatically called.
Example 9.5: void test( x )
{
—————
—————
}
main()
{
x a;
test(a); //copy constructor is invoked
}
5. Copy constructor is invoked when an object returns a value.
Example 9.6:
class measure
{
int feet;
float inches;
measure sum(measure&);
};
226 Constructors and Destructors
#include<iostream.h>
class copy
{
int var;
public:
copy(int temp)
{
var = temp;
}
int calculate()
{
int fact, i;
fact = 1;
for(i = 1; i <= var; i++)
fact = fact * i;
return fact;
}
};
void main()
{
int n;
cout<<"Enter the number: ";
cin>>n;
copy obj(n);
copy cpy = obj;
cout<<"Before copying: "<<n<<"! = "<<obj.calculate()<<endl;
cout<<"After copying: "<<n<<"! = "<<cpy.calculate()<<endl;
}
Constructors and Destructors
227
Enter the number: 5
Before copying: 5! = 120
After copying: 5! = 120
#include<iostream.h>
class simpleinterest
{
private:
float p, r, t, si;
public:
simpleinterest() //default constructor
{ }
simpleinterest(float x, float y, float z)//parameterized
{ //constructor
p = x;
r = y;
t = z;
}
void computesi()
{
cout<<"Simple interest is :"<< (p * r * t)/100.0;
}
};
void main()
{
simpleinterest si1, si2(10000.0, 12.0, 2.0);
si2.computesi();
}
num a;
a.display();
getch();
return 0;
}
In constructor:
Value of x = 100
In destructor
In the above program after executing the program, before the control is
transferred out of the function main(), the destructor ~string() is invoked for
each object a, so that memory allotted for data member is de allotted. The object
y and p are deleted using the destructor.
Points to remember:
A Constructor is a special member function that is executed automatically
whenever an object of a class is created.
Constructors should have either public or protected access.
The three types of constructors are default constructor, parameterized
constructor and copy constructor.
A constructor that does not take any arguments is a default constructor.
A constructor that takes one or more arguments is called parameterized
constructor.
Parameterized constructor can be invoked by explicit or implicit call.
Copy constructor is a parameterized constructor using which one object
can be copied to another object.
Constructor overloading means passing arguments to the constructor.
Destructors are member functions that destroy an object automatically.
One mark questions:
1. What is a constructor?
2. Write one reason which defines the need to use a constructor.
Simplify
3. What should be the access parameters for constructor declaration?
4. Can a constructor return a value to a calling function?
5. How many types of constructors are there?
6. What is a default constructor?
7. What is the drawback of default constructor?
8. Is it possible to overload a default constructor?
Constructors and Destructors
231
9. What is a parameterized constructor?
10. Write any one feature of parameterized constructor.
11. Name two methods through which constructors can be invoked.
12. What is an explicit call?
13. What is an implicit call with reference to constructors?
14. When is =used with constructors?
15. What is a copy constructor?
16. Write the syntax for declaration of copy constructor.
17. Can a copy constructor be invoked explicitly?
18. What is meant by constructor overloading?
19. What is a destructor?
20. Which operator is used with destructor?
Two marks questions:
1. What is a constructor? Give an example
2. Why are constructors needed in a program? Justify
3. Write the syntax and example for default constructor.
4. Mention the features of parameterized constructors.
5. Which are the different methods through which constructors are invoked?
6. Write an example to show the use of parameterized constructor through
explicit call.
7. When is copy constructor used in a program?
8. Write syntax and example for copy constructor.
Three marks questions:
1. Mention three types of constructors
2. What are the features of default constructors?
3. What are the disadvantages of default constructor?
4. Write short notes for constructor overloading.
Five marks questions:
1. Write the rules for writing a constructor function.
2. Explain default constructor with syntax and example.
3. Explain parameterized constructor with syntax and example.
4. Explain with an example to show how a constructors is invoked explicitly.
5. Explain the features of copy constructor.
6. Explain destructors with syntax and example.
*****
232 Inheritance
CHAPTER - 10
INHERITANCE
OBJECTIVES
10.1 Introduction:
Inheritance is another important aspect of object oriented programming.
C++ supports this concept. C++ classes can be used in several ways. This is basically
done by creating new classes, reusing the properties of existing one.
C++ allows the user to create a new class (derived class) from an existing
class (base class). The derived class inherits all features from a base class and it
can have additional features of its own.
The private members of a base class can not be inherited to the derived
class.
The protected members of a base class stay protected in a derived class.
class subclass: public superclass
class student //base class
{
private:
int rollno;
char name[50];
float per;
public:
void input();
void output();
};
class comp: public student //publicly derived class
{
private:
int marks;
public:
void read();
void write();
};
10.4.2. Private Inheritance
The public members of a base class become the private members of the
derived class.
The private members of a base class cannot be inherited to the derived
class.
The protected members of a base class stay protected in a derived class.
10.4.3. Protected Inheritance
The public members of a base class become protected in a derived class.
The private members of a base class cannot be inherited to the derived
class.
The protected members of a base class stay protected in a derived class.
class subclass : protected superclass
10.5 Levels of Inheritance
A derived class extends its features by inheriting some or all the properties
from its base class and adding new features of its own. While inheriting, the derived
class can share properties from:
Inheritance 237
Only one class
More than one class
More than one level
Based on this relationship, inheritance can be classified into five forms.
1. Single inheritance
2. Multilevel inheritance
3. Multiple inheritance
4. Hierarchical inheritance.
5. Hybrid inheritance
10.5.1 Single Inheritance
If a class is derived from a single base class, it is called as single inheritance.
Base Father
Derived class-n
238 Inheritance
Prince
Derived class
Base
Staff
Base
Hierarchical inheritance
void display()
{
cout<<“roll no: “<< rollno <<endl;
cout<<“name : “<<name <<endl;
}
};
class derive: public base
{
private:
int m1;
int m2;
int t;
public:
void read1()
{
cout<<“enter first marks and second marks: ”<<endl;
240 Inheritance
cin>>m1>>m2;
t = m1+m2;
}
void display1()
{
cout<<"First marks = "<<m1<<endl;
cout<<"Second marks = "<<m2 <<endl;
cout<<"Total marks = "<<t<<endl;
}
};
void main()
{
derive ob;
clrscr();
ob.read();
ob.read1();
ob.display();
ob.display1();
getch();
}
Base class - A
When two or more objects are derived from a common base class,
we can prevent multiple copies of the base class being present in an object
derived from those objects by declaring the base class as virtual when it is
being inherited. Such a base class is known as virtual base class. This
can be achieved by preceding the base class name with the word virtual.
Example: class A
{
————
————
};
class B: virtual public A
{
————
————
};
class C: virtual public A
{
————
————
};
class D: public B, public C
{
————
————
};
242 Inheritance
Review questions
1. What is inheritance?
2. How to implement inheritance?
3. What is base class?
4. What is derived class?
5. What is public access specifier?
6. What is private access specifier
7. Mention any one advantage of inheritance?
8. Is inheritance possible in c?
9. What is the use of protected access specifier?
10. What is the use of public access specifier?
11. What is the use of private access specifier?
12. What is singe inheritance?
13. What is multilevel inheritance?
14. What is hierarchical inheritance?
15. What is hybrid inheritance?
16. What is multiple inheritance?
17. What is virtual base class?
18. What is an abstract class?
19. When is it necessary to use inheritance?
20. What is visibility mode?
Two marks questions:
CHAPTER-11
POINTERS
Objectives:
We know that variables are declared before they are used in a program.
Declaration of a variable tells the compiler to perform the following.
Allocate a location in memory. The number of location depends on data
type.
Establish relation between address of the location and the name of the
variable.
Consider the declaration, int num;
Pointer 249
This declaration tells the compiler to reserve a location in memory. We know
that the size of int type is two byte. So the location would be two bytes wide.
Address num
100 15
101
In the above figure, num is the variable that stores the value 15 and address
of num is 100. The address of a variable is also an unsigned integer number. It
can also be retrieved and stored in another variable.
Pointer:
A pointer is a variable that holds a memory address, usually the location
of another variable in memory.
11.3 Declaration and Initialization of pointer:
The general form is, data-type *variable_name;
data-type is any valid data type supported by C++ or any user defined type and
variable_name is the name of pointer variable. The presence of * indicates that it
is a pointer variable.
Defining a Pointer Variable:
int *iptr; iptr is declared to be pointer variable of int type.
float *fptr; fptr is declared to be pointer variable of float type.
char *cptr; cptr is declared to be pointer variable of character type.
Pointer Variables Assignment:
We can assign the address of a variable to a pointer variable as follows:
int num = 25;
int *iptr;
iptr = #
In the above example, the variable num (=25) is assigned to pointer variable iptr.
11.4 The address-of operator (&):
& is a unary operator that returns the memory address of its operand. For
example, if var is an integer variable, then &var is its address. This operator has
the same precedence and right-to-left associativity as the other unary operators.
You should read & operator as “the address-of” which means &var will be
read as “the address of var”.
Example: int num = 25;
Pointer
250
int *iptr;
iptr = # // The Address of Operator &
11.5 Pointer operator or Indirection Operator (*):
The second operator is Indirection Operator *, and it is the complement of
&. It is a unary operator that returns the value of the variable located at the
address specified by its operand.
Example:
int num = 25;
int *iptr; //Pointer operator (Indirection Operator *):
iptr = #
The following program executes the above two operations
#include <iostream>
#include <iomanip.h>
void main( )
{
int var;
int *ptr;
int val;
var = 3000;
ptr = &var;
val = *ptr;
cout << “Value of var: “ << var << endl;
cout << “Value of ptr: “ << ptr << endl;
cout << “Value of val: “ << val << endl;
}
Value of var: 3000
Value of ptr: 0xbff64494
Value of val: 3000
11.6 Pointer Arithmetic:
As you understood, pointer is an address which is a numeric value.
Therefore, you can perform arithmetic operations on a pointer just as you can
on a numeric value.
There are four arithmetic operators that can be used on pointers: ++, —, +, and
. (dot operator).
Following operations can be performed on pointers.
We can add an integer value to a pointer.
We can subtract an integer value from a pointer,
Pointer 251
We can compare two pointers, if they point the elements of the same array
We can subtract one pointer from another pointer if both point to the
same array.
We can assign one pointer to another pointer provided both are of same
type.
Following operations cannot be performed on pointers.
Addition of two pointers.
Subtraction of one pointer from another pointer when they do not point to
the same array.
Multiplication of two pointers.
Division of two pointers.
Example:
a. Suppose if p is an integer pointer then p++ will increment p by 2 bytes.
Each time a pointer is incremented by 1, it points to the memory location
of the next element of its base type.
b. Suppose if p is a char pointer then p++ will incremented p by 1-byte.
c. p-- each time a pointer is decremented by 1, it points to the memory
location of the previous element of its base type.
d. p=p + integer value.
p=p - integer value.
11.7 Pointers and Arrays:
There is a close relationship between arrays and pointers in C++.
Consider the declaration. int a[6];
The elements of the array can be referred to in the program as a[0], a[1],
…. , a[9]. When the program is compiled, the compiler does not save the addresses
of all the elements, but only the address of the
first element, a[0]. When the program needs to
access any element, a[i], it calculates its address
A[0] A[1] A[2] A[3] A[4] by adding i units to the address of a[0]. The
number of bytes in each “unit” is, in our example,
equal to the sizeof(int). i.e., 2. In general, it is equal
to the number of bytes required to store an element of the array.
The address of a[0] can be explicitly obtained using the & (address-of)
operator. i.e., &a[0]. Since the data type of a[0] is int, the data type of &a[0] is, as
usual, int* (pointer to int).
Pointer
252
C++ allows us to use the name of the array a, without any subscript, as
another name for &a[0].
The following example shows the relationship between pointer and one-
dimensional array.
#include<iostream.h>
#include<conio.h>
#include<iomanip.h>
void main( )
{
int a[10], i, n;
cout<<"How many elements? ";
cin>>n;
cout<<"Enter array elements: ";
for(i=0; i<n; i++)
cin>>*(a+i);
cout<<"The given array elements are ";
for(i=0; i<n; i++)
cout<<setw(4)<<*(a+i);
getch();
}
How many elements? 5
Enter array elements: 1 2 3 4 5
The given array elements are 1 2 3 4 5
11.8 Array of pointers:
As we know that there is an array of integers, array of float, similarly,
there can be an array of pointers. Since we know that pointer is a variable which
stores address of another variable, an array of pointers means that it is a collection
of addresses.
The example below shows the array of pointers.
int *iptr[5];
int i=10, j=20, k=30, l=40, m=50;
iptr[0] = &i; *iptr[0] = 10;
iptr[1] = &j; *iptr[1] = 20;
iptr[2] = &k; *iptr[2] = 30;
iptr[3] = &l; *iptr[3] = 40;
iptr[4] = &m; *iptr[4] = 50;
Pointer 253
11.9 Pointers and Strings:
We have already discussed that there is a close relationship between array
and pointers. Similarly there is also a close relationship between strings and
pointers in C++. String is sequence of characters ends with null (‘\0’) character.
Suppose we have declared an array of 5 elements of the data type character.
char s[5];
char *cptr;
cptr = s;
Here, s is array of characters (strings). cptr is character pointer to string. s
also represents character pointer to string.
The elements of the array can be referred to in the program as s[0], s[1],
…. , s[5]. When the program is compiled, the compiler does not save the addresses
of all the elements, but only the name of the array. Here, s gives the base
address of the array. i.e., the address of the first character in the string variable
and hence can be regarded as pointer to character. Since we know that string
always end with null character, it is enough for us to know the starting address
of a string to be able to access entire string. The number of bytes allocated for a
string is determined by the number of characters within string.
Let us now consider a string constant “HELLO”. s is pointer to the
memory location where ‘H’ is stored. Here, s can be viewed as a character array
of size 6, the only difference being that a can be reassigned another memory
location.
char s[5] = “Hello”; H E L L O \0
s[0] s[1] s[2] s[3] s[4] s[5]
Here, s gives address of ‘H’.
*a gives ‘H’
a[0] gives ‘H’
a++ gives address of ‘E’
*a++ gives ‘E'
11.10 Pointers as Function Parameters.
A pointer can be a parameter. It works like a reference parameter to allow
change to argument from within the function.
void swap(int *x, int *y)
{
int temp;
temp = *x;
*x = *y;
*y = temp;
}
swap(&num1, &num2);
Pointer
254
11.11 Pointers and Structures
We can create pointers to structure variables.
struct student
{
int rollno;
float fees;
};
student s;
student *sp = &s;
(*sp).rollno = 104;
The above statements can be written using the operator -> as
ptr -> member:
sp -> rollno = 104;
11.12. Memory allocation of pointers (Dynamic and Static )
The compiler allocates the required memory space for a declared variable.
For example, integer variable it reserves 2- bytes, float variable it reserves 4-
bytes, character variable it reserves 1-byte and so on. Therefore every data and
instruction that is being executed must be allocated some space in the main or
internal memory. Memory allocation is done in two ways:
Static allocation of memory
Dynamic allocation of memory
11.12.1 Static allocation of memory
In the static memory allocation, the amount of memory to be allocated is
predicted and pre known. This memory is allocated during the compilation itself.
All the variables declared normally, are allocated memory statically.
Example: int a; //Allocates 2 bytes of memory space during the
//compilation time.
11.12.2 Dynamic allocation of memory ( new and delete)
In the dynamic memory allocation, the amount of memory to be allocated
is not known. This memory is allocated during run-time as and when required.
C++ supports dynamic allocation and deallocation of objects using the
new and delete operators. These operators allocate memory for objects from a
pool called the free store. The new operator calls the special function operator
new and the delete operator calls the special function operator delete.
We can allocate storage for a variable while program is running by using
new operator. Dynamic allocation is perhaps the key to pointers. It is used to
allocate memory without having to define variables and then make pointers
Pointer 255
point to them. Although the concept may appear confusing, it is really simple.
The following codes demonstrate how to allocate memory for different variables.
To allocate memory of type integer, int *iptr = new int;
int *pNumber;
pNumber = new int;
The first line declares the pointer, pNumber. The second line then allocates
memory for an integer and then makes pNumber point to this new memory.
Here is another example, this time using a double:
double *pDouble;
pDouble = new double;
To allocate memory for array, double *dptr = new double[25];
To allocate dynamic structure variables or objects,
student sp = new student; //student is tag name of structure
The formula is the same every time, so you can’t really fail with this bit.
What is different about dynamic allocation, however, is that the memory you
allocate is not deleted when the function returns, or when execution leaves the
current block. So, if we rewrite the above example using dynamic allocation, we
can see that it works fine now:
#include<iostream.h>
#include<conio.h>
#include<iomanip.h>
int *p;
void SomeFunction()
{
// make p pointer point to a new integer
p = new int;
*p = 25;
}
void main()
{
SomeFunction(); // make pPointer point to something
cout<<"Value of *p: "<<*p;
} Output Value of *p: 25
n o d e * n e x t ;
CHAPTER 12
OBJECTIVES
12.1 Introduction:
We have already used the cin and cout for handling the input and ouput
operations. They are used to accept inputs through keyboard and display outputs
on the screen. C++ provides a rich set of operations for both unformatted and
formatted I/O operations. In C++, these IO operations are implemented through
iostream library.
The C++ standard libraries provide an extensive set of input/output
capabilities which we will see in subsequent topics. This chapter will discuss
very basic and most common I/O operations required for C++ programming.
C++ I/O occurs in streams, which are sequences of bytes. If bytes flow
from device like a keyboard, a disk drive, or a network connection etc. to main
memory, this is called input operation and if bytes flow from main memory to a
device like a display screen, a printer, a disk drive, or a network connection etc.,
this is called output operation.
Most computer programs work with files. This is because files help in
storing information permanently. Word processors create document files.
Database programs create files of information. Compilers read source files and
generate executable files. So, we see, it is the files that are mostly worked with,
inside programs. A file itself is a bunch of bytes stored on some storage device
like tape or magnetic disk etc.
In C++, file input/output facilities are implemented through a header file
of C++ standard library. This header file is fstream.h.
In C++, a file, at its lowest level, is interpreted simply as a sequence, or
stream of bytes. In C++, file I/O library manages the transfer of these bytes. At
this level, the notion of a data type is absent.
On the other hand, file, at user level, consists of a sequence of possibly
intermixed data types-characters, arithmetic values and class objects.
The fstream library predefines a set of operations for handling files related
input and output. It defines certain classes that help to perform file input and
output. For example, ifstream class ties a file to the program for input. ofstream
class ties a file to the program for output and fstream classifies a file to the
program for both input and output. File manipulation and related operations
using streams are the topics we are going to discuss in this chapter.
268 Data file handling
ofstream _object is an object of type ofstream and “file name” is any valid
identifier of a file to be opened for output purpose only.
Example: ofstreamfout(“results.dat”); //output only
ofstreamfout(“text.dat”); //output only
fout is declared to be an object of ofstream type and it is made to represent
the file results.dat and text.dat opened for output purpose only.
The syntax of opening a file for input purpose only using an object of
ifstream class and the constructor is as follows.
ifstream ifstream _object(“file_name”);
ifstream _object is an object of type ifstream and “file name” is any valid
identifier name of a file to opened for input purpose only.
Example: ifstream fin(“results.dat”); //input only
ifstream fin(“text.dat”); //input only
fin is declared to be an object of ifstream type and it is made to represent
the file results.dat and text.dat opened for input purpose only.
12.4.2 Opening file using open( ):
The syntax for opening a file for output purpose only using an object of
ofstream class and open( ) member function is as follows:
ofstream-object.open(“filename”)
ofstream-object is an object of type ofstream and “filename” is any valid
name of a file to be opened for output purpose only.
Example: ofstream ofile;
ofile.open(“data1”);
ofile.open(“text.dat”);
ofile is declared to be an object of ofstream type and is made to represent
the file data1 or text.dat opened for output purpose only.
The syntax for opening a file for input purpose only using an object of
ifstream class and open( ) member function is as follows:
ifstream-object.open(“filename”)
ifstream-object is an object of type ifstream and “file name” is any valid
name of a file to be opened for input purpose only.
Example: ifstream ifile;
ifile.open(“data1”);
ifile.open(“text.dat”);
272 Data file handling
All these flags can be combined using the bitwise operator OR (|).
Example: fstream fout(“text.dat”,ios::out); open text.dat in output mode
fstream fin(“text.dat”,ios::in); open text.dat in input mode
fstream file;
file.open (“example.bin”, ios::out | ios::app | ios::binary);
If we want to open the file “example.bin” in binary mode to add data we
could do it by the above call to member function.
Data file handling 273
String I/O:
The getline( ) function:
It is used to read a whole line of text. It belongs to the class ifstream.
Syntax: fin.getline(buffer, SIZE);
Reads SIZE characters from the file represented by the object fin or till
the new line character is encountered, whichever comes first into the buffer.
Example: char book[SIZE];
fstream fin;
fin.getline(book, SIZE);
Input and output operation on binary files:
The binary files are of very much use when we have to deal with database
consisting of records. Since the records usually comprise heterogeneous data
types, the binary files help optimize storage space and file I/O would be faster
when compared to text files. Binary files needs following types of input and
output operations.
write() member function
read() member function
write( ): The write() member function belongs to the class ofstream and which
is used to write binary data to a file.
Syntax: ofstream_object.write((char *) &variable, sizeof(variable));
fout is an object of type ofstream. The function requires two arguments.
The first argument ofstream_object is the address of the variable, the contents of
which are written to the file and the second argument is the size of the variable.
The address of the variable is type casted to pointer to char type. It is because
the write function does not bother to know the type of variable. It requires data
in terms of only bytes. The function writes the contents of variable to the file
represented by the object fout.
Example: student s;
ofstream fout(“std.dat”,ios::binary);
fout.write((char*) &s, sizeof(s));
Write the contents of the object s to the file std.dat.
read( ): The read() member function belongs to the class ifstream and which
is used to read binary data from a file.
Syntax: ifstream_object.read((char *) &variable, sizeof(variable));
ifstream_object is an object of type ifstream. The function requires two
arguments. The first argument is the address of the variable, the contents of
which are read from the file and the second argument is the size of the variable.
Data file handling 275
The address of the variable is type casted to pointer to char type. It is because
the read function does not bother to know the type of variable. It requires data
in terms of only bytes. The function reads a record from the file represented by
the object fin to the object std.
Example: student s;
ifstream fin(“std.dat”,ios::binary);
fin.read((char*) &s, sizeof(s));
Read a student record from the file std.dat into the object s.
12.6. Detecting end of file:
While reading the contents of a file, care has to be taken to see to it that
the operation does not cross the end of file. The ios class provides a member
function by name eof(), which helps in detecting the end of file. Once the end of
file is detected with the use of eof() member function, we can stop reading further.
eof() returns true (non zero) if end of file is encountered while reading;
otherwise return false(zero).
if(fin.eof())
{
statements;
}
This is used to execute set statements on reaching the end of the file
represented by the object fin.
while (!fin.eof())
{
statements;
}
This is used to execute set statements as long as the end of the file fin is
not reached.
12.7. File pointers and their manipulation:
In C++, the file I/O operations are associated with the two file pointers,
known as get pointer and the put pointer. These are synonymous for input
pointer and output pointer respectively. They are useful in traversing the opened
file while reading or writing.
ifstream, like istream, has a pointer known as the get pointer that
points to the element to be read in the next input operation.
ofstream, like ostream, has a pointer known as the put pointer that
points to the location where the next element has to be written.
276 Data file handling
The offset takes long data type and seekdir (direction for seeking the offset
position inside a file) takes one of the following three seek direction constants.
These constants are defined in ios class.
Constant Meaning
ios::beg Offset specified from the beginning of the file
ios::cur Offset specified from the current position of the get pointer
ios::end Offset specified from the end of the file
Examples: inf.seekg(0, ios::beg);
Move the get pointer to the 0th byte (i.e., beginning of the file).
inf.seekg(20, ios::beg);
Moves the get pointer to the 20th byte (i.e., from current position of the file
in forward direction).
inf.seeg(-20, ios::beg );
The above example tells that the get pointer points to 20th byte in a file
from end of file in backward direction.
seekp():
Move the put pointer to a specified location from the beginning of a file.
There are two types:
seekp(long);
seekp(offset, seekdir);
The seekp(long) moves the put pointer to a specified location from the
beginning of a file.
Example: inf.seekg(20) ;
The above example tells that the put pointer points to 20th byte in a file
from 0th byte.
The seekp(offset, seekdir) has two arguments offset and seekdir. The offset
indicates the number of bytes the put pointer is to be moved from seekdir
position.
The offset takes long data type and seekdir (direction for seeking the offset
position inside a file) takes one of the following three seek direction constants.
These constants are defined in ios class (see above table).
Examples: inf.seekp(0, ios::beg);
Move the put pointer to the 0th byte (i.e, beginning of the file) for writing.
inf.seekg(20, ios::beg) ;
278 Data file handling
Move the put pointer to the 20th byte (i.e, from current position of the file
in forward direction) for writing.
inf.seekg(-20, ios::beg) ;
The above example tells that the put pointer points to 20th byte in a file
from end of file in backward direction.
tellg( ) member function:
The ifstream class provides the member function name tellg(). The purpose
of the function is to return current position of the get pointer.
Syntax: int position;
position = fin.tellg();
tellp() member function:
The ifstream class provides the member function name tellp( ); The purpose
of the function is to return current position of the put pointer.
Syntax: int position;
position = fin.tellp();
Basic operation on binary file in C++
tellg(): The ifstream class provides the member function name tellg(); The
purpose of the function is to return current position of the get pointer.
tellp(): The ifstream class provides the member function name tellp(); The
purpose of the function is to return current position of the put pointer.
CHAPTER 13
DATABASE CONCEPTS
OBJECTIVES
13.1 Introduction :
The large and complex data which are collected, entered, stored and accessed
based on the users needs are in the form of queries. Unique softwares are
developed and used, which are highly secured and complex. This chapter will
illustrate the database concepts.
Today the database is used everywhere and in all walks of life. The database
is becoming the backbone of all the softwares from standalone, client-server,on-
line, mainframe, supercomputers etc. For exam pl e use in business,
government agency, service organization etc. Wherever the data and information
is required, there the database software is used and the results are presented in
the form of reports or graphical representation, which are easier for
understanding, so that furture activities can be carried out based on these reports.
One of the area where database is used can be schools; for example. The Fees
payment software. The basic requirements for new student admission are Name,
student id, admission no, father name, class, section, amount, date of entry into
the school are entered and saved. Some of the activities can be admission fees/
annual fees, monthly fees, late payment etc., created and the respective reports
are generated.
DATABASE
284 Data Concepts
The fact is something that is really occurred or is actually the case. The
things that are happening and happened in real form or virtual form are
considered to be fact. The fact is pursued by sense organs.
The process of converting fact to data will be the first task, for any person
in database concepts. The human intervention is mandatory for converting from
fact to data form. The data may be in the form of letters, numbers, symbols,
images, sound, video etc. The origin of fact can be from the organization/within
or outside organization or any part of universe. For example the marks obtained
by the student in the exam is 80, 80 is the fact, on the marks card the 80
entered will be in numberic symbols which is data.
Data Concepts 285
The different forms of data and its representation is illustrated. One such form
is sound represented using musical notes (software generated), these notes is
stored in the form of bytes in the sound file(software digitized). In the
hardware data is stored in the form of bits.
For example, in the marks card of the student total marks, percentage
and the result are processed data known as the information.
Initially, the computer files within the file system were similar to the manual
files. The description of computer files requires a specialized vocabulary.
Every discipline develops its own terminology to enable its practitioners to
communicate clearly.
Differences between Manual and Computerized data processing
1. Data input– This is any kind of data- letters, numbers, symbols, shapes,
images or whatever raw material put into the computer system that needs
processing. Input data is put into the computer using a keyboard, mouse or
other devices such as the scanner, microphone and the digital camera. In general
data must be converted to computer understandable form (English to machine
code by the input devices).
3. Storage - Data and information not currently being used must be stored so it
can be accessed later. There are two types of storage; primary and secondary
storage. Primary storage is the computer circuitry that temporarily holds data
Data Concepts 287
4 . O u t p u t – T h e
result(information)
obtained after processing
the data must be
presented to the user in
user understandable form.
The result may be in form
of reports(hardcopy/
softcopy). Some of the
output can be animated
Fig. 13.2 Data Processing cycle
with sound and video/
picture.
File : File is basic unit of storage in computer system. The file is the large
collection of related data.
The primary goal of a DBMS is to provide a way to store and retrieve database
information that is both convenient and efficient.
Serial File Organization : With serial file organization, records are arranged
one after another, in no particular order-other than, the chronological order in
which records are added to the file. Serial organization is commonly found in
the transaction data. Where records are created in a file in the order in which
transaction takes place. Serial file organization provides advantages like fast
294 Data Concepts
Two-tier Client / Server architecture is used for User Interface program and
Application Programs that runs on client side. An interface called ODBC (Open
Database Connectivity) provides an API that allows client side program to call
the DBMS. Most DBMS vendors provide ODBC drivers. A client program may
connect to several DBMS's. In this architecture some variation of client is also
possible for example in some DBMS's more functionality is transferred to the
client including data dictionary, optimization etc. Such clients are called Data
server.
structures and conceptual tools that is used to describe the structure (data
types, relationships, and constraints) of a database.
A data model not only describes the structure of the data, it also defines a set
of operations that can be performed on the data. A data model generally
consists of data model theory, which is a formal description of how data may
be structured and used, and data model instance, which is a practical data
model designed for a particular application. The process of applying a data
model theory to create a data model instance is known as data modeling.
A Database model defines the logical design of data. The model describes the
relationships between different parts of the data.
In history of database design, three models have been in use.
* Hierarchical Model
* Network Model
* Relational Model
13.11.1 Hierarchical Model
The hierarchical data model is the oldest type of data model, developed by IBM
in 1968. This data model organizes the data in a tree-like structure, in which
each child node (also known as dependents) can have only one parent node.
The database based on the hierarchical data model comprises a set of records
connected to one another through links. The link is an association between two
or more records. The top of the tree structure consists of a single node that does
not have any parent and is called the root node.
The root may have any number of dependents; each of these dependents may
have any number of lower level dependents. Each child node can have only one
parent node and a parent node can have any number of (many) child nodes. It,
therefore, represents only one-to-one and one-to-many relationships. The
collection of same type of records is known as a record type.
For simplicity, only few fields of each record type are shown. One complete
record of each record type represents a node.
300 Data Concepts
In this model each entity has only one parent but can have several children . At
the top of hierarchy there is only one entity which is called Root.
Hierarchical Model Example
Advantage Dis-advantage
The hierarchical data model is that The main drawback of this model is
the data access is quite predictable that the links are ‘hard coded’ into
in the structure and, therefore, both the data structure, that is, the link is
the retrieval and updates can be permanently established and cannot
highly optimized by the DBMS. be modified. The hard coding makes
the hierarchical model rigid. In
addition, the physical links make it
difficult to expand or modify the
database and the changes require
substantial redesigning efforts.
hierarchical data model, the data is organized in the form of trees and in network
data model, the data is organized in the form of graphs.
In the network model, entities are organized in a graph, in which some
entities can be accessed through several path
Advantage Dis-advantage
The network data model is that a The network data model is that it
parent node can have many child can be quite complicated to maintain
nodes and a child can also have all the links and a single broken link
many parent nodes. Thus, the can lead to problems in the
network model permits the modeling database. In addition, since there are
of many-to-many relationships in no restrictions on the number of
data. relationships, the database design
can become complex.
the relational model has become more programmer friendly and much more
dominant and popular in both industrial and academic scenarios. Oracle, Sybase,
DB2, Ingres, Informix, MS-SQL Server are few of the popular relational DBMSs.
You can clearly see here that student name Daryl is used twice in the table and
subject *maths* is also repeated. This violates the *First Normal form*. To reduce
above table to *First Normal form* break the table into two different tables
Data Concepts 305
A table to be normalized to Second Normal Form should meet all the needs of
First Normal Form and there must not be any partial dependency of any column
on primary key. It means that for a table that has concatenated primary key,
each column in the table that is not part of the primary key must depend upon
the entire concatenated key for its existence. If any column depends only on
one part of the concatenated key, then the table fails Second normal form. For
example, consider a table which is not in Second normal form.
Library Table : Fig 13.19 Student table with 1NF rule rewritten
Library_id S_Name Issue_id Issue_name Book_detail
101 RAMU 10 Rakesh C++
102 RAMU 11 Rakesh Java
103 Zama 12 Gopal MATHS
104 SATISH 13 Gopal MATHS
To reduce Library table to Second Normal form break the table into
following three different tables.
Library_id S_Name
Library_id S_Name
101 RAMU
102 RAMU
103 Zama
104 SATISH
Issue_Detail Table :
Issue_id Issue_name
10 Rakesh
11 Rakesh
12 Gopal
13 Gopal
Book_Detail Table :
Now all these three table comply with Second Normal form.
Library_id S_Name Issue_Detail Table :
Fig 13.20 2NF Library Tablewith primary key and Issue key
Data Concepts 307
Now all these three table comply with Second Normal form.
Third Normal form applies that every non-prime attribute of table must be
dependent on primary key. The transitive functional dependencyshould be
removed from the table. The table must be in Second Normal form.
For example, consider a table with following fields.
Student_Detail Table :
In this table Student_id is Primary key, but street, city and state depends upon
pin. The dependency between pin and other fields is called transitive dependency.
Hence to apply 3NF, we need to move the street, city and state to new table, with
pin as primary key.
Address Table :
3NF does not deal satisfactorily with the case of a relation with overlapping
candidate keys
A relation is in BCNF is, and only if, every determinant is a candidate key.
R(a,b,c,d)
a,d -> b
Here, the first determinant suggests that the primary key of R could be changed
from a,b to a,c. If this change was done all of the non-key attributes present in
R could still be determined, and therefore this change is legal. However, the
second determinant indicates that a,d determines b, but a,d could not be the
key of R as a,d does not determine all of the non key attributes of R (it does not
determine c). We would say that the first determinate is a candidate key, but the
second determinant is not a candidate key, and thus this relation is not in
BCNF (but is in 3rd normal form).
„A relation R(X) is in Boyce–Codd Normal Form if for every non-trivial functional
dependency Y->Z defined on it, Y contains a key K of R(X). That is, Y is a
superkey for R(X).
1) Entity
An Entity can be any object, place, person or class. In E-R Diagram, an entity is
represented using rectangles. Consider an example of an Organization.
Employee, Manager, Department, Product and many more can
2) Attribute
Composite Attribute : An
attribute can also have their own
attributes. These attributes are
known as Composite attribute.
3) Relationship
A Relationship describes relations between entities. Relationship is
represented using diamonds.
Relationship Relationship example
Binary Relationship
one-to-one example
2. One to Many : It reflects business rule that one entity is associated with
many number of same entity. For example, Student enrolls for only one Course
but a Course can have many Students.
One to Many
The arrows in the diagram describes that one student can enroll
for only one course.
3. Many to Many : The above diagram represents that many students can
enroll for more than one courses.
Many to Many
13.13.3 Cardinality
Generalization Specialization
Fig13.37 Aggregration
Aggregration : Aggregration is a process when
relation between two entity is treated as a single
entity. Here the relation between Center and Course, is acting as an Entity in
relation with Visitor.
13.14 Keys
The word “key” is used in the context of relational database design. They are
used to establish and identify relation between tables. The key is a set of one or
more columns whose combined values are unique among all occurrences in a
given table.
316 Data Concepts
3. Alternate key/Secondary key(sk): The alternate keys of any table are simply
those candidate keys which are not currently selected as the primary key.
An alternative key is a function of all candidate keys minus the primary
key.
5. Super Key : A superkey is basically all sets of columns for which no two
rows share the same values for those sets. An attribute or set of attributes
that uniquely identifies a tuple within a relation/table. Super Key is a
superset of Candidate key.
6. Foreign key(fk) :A foreign key is a field in a relational table that matches
the primary key column of another table. The foreign key can be used to
cross-reference tables.
Table Employees
Employee_id Name Age city Salary Car_loan_id
1 Rajappa 42 Tumkur 42000 585
Table BMWcars
Car_load_id Model Loanamount EMI Noof EMI Balance
585 Basic 1800000 80000 225 1000000
1.Composite Key : Key that consists of two or more attributes that uniquely
identify an entity occurrence is called
Composite key. But any attribute
that makes up the Composite key is
not a simple key in its own.
Example: Consider a Relation or
Table R1. Let A,B,C,D,E are the
attributes of this relation.
R(A,B,C,D,E)
A?BCDE This means the attribute 'A' uniquely determines the other attributes
B,C,D,E.
BC?ADE This means the attributes 'BC' jointly determines all the other attributes
A,D,E in the relation.
Primary Key :A
Candidate Keys :A, BC
Super Keys : A,BC,ABC,AD
Note : ABC,AD are not Candidate Keys since both are not minimal super keys.
Relational Algebra is :
the formal description of how a relational database operates
an interface to the data stored in the database itself
the mathematics which underpin SQL operations
Operators in relational algebra are not necessarily the same as SQL operators,
even if they have the same name. For example, the SELECT statement exists in
SQL, and also exists in relational algebra. These two uses of SELECT are not the
same. The DBMS must take whatever SQL statements the user types in and
translate them into relational algebra operations before applying them to the
database.
Terminology
Relation – a set of tuples.
Tuple – a collection of attributes which describe some real world entity.
Attribute – a real world role played by a named domain.
Domain – a set of atomic values.
Set – a mathematical definition for a collection of objects which
contains no duplicates.
Data Concepts 319
Operators – Write
INSERT – provides a list of attribute values for a new tuple in a relation.
This operator is the same as SQL.
DELETE – provides a condition on the attributes of a relation to
determine which tuple(s) to remove from the relation. This operator is the
same as SQL.
MODIFY – changes the values of one or more attributes in one or more
tuples of a relation, as identified by a condition operating on the attributes of
the relation. This is equivalent to SQL UPDATE.
Operators – Retrieval
There are two groups of operations:
Mathematical set theory based relations:
UNION, INTERSECTION, DIFFERENCE, and CARTESIAN PRODUCT.
SELECT EMPNO
FROM EMPLOYEE
WHERE DEPTNO=1;
Fig.13.41 Select and project
Figure : Mapping select and project
Set Operations – semantics
Consider two relations R and S.
UNION of R and S
the union of two relations is a relation that includes all the tuples that are
either in R or in S or in both R and S. Duplicate tuples are eliminated.
INTERSECTION of R and S
the intersection of R and S is a relation that includes all tuples that are
both in R and S.
DIFFERENCE of R and S
the difference of R and S is the relation that contains all the tuples that are
in R but that are not in S.
For set operations to function correctly the relations R and S must be union
compatible. Two relations are union compatible if
the domain of each attribute in column order is the same in both R and
S.
Data Concepts 321
UNION Example
Fig.13.42 Union
INTERSECTION Example
Fig.13.43 Intersection
DIFFERENCE Example
Fig.13.44 Difference
322 Data Concepts
CARTESIAN PRODUCT
The Cartesian Product is also an operator which works on two sets. It is
sometimes called the CROSS PRODUCT or CROSS JOIN.
It combines the tuples of one relation with all the tuples of the other relation.
CARTESIAN PRODUCT example
Natural Join
Invariably the JOIN involves an equality test, and thus is often described as an
equi-join. Such joins result in two attributes in the resulting relation having
exactly the same value. A ‘natural join’ will remove the duplicate attribute(s).
In most systems a natural join will require that the attributes have the
same name to identify the attribute(s) to be used in the join. This may
require a renaming mechanism.
If you do use natural joins make sure that the relations do not have two
attributes with the same name by accident.
OUTER JOINs
Notice that much of the data is lost when applying a join to two relations. In
some cases this lost data might hold useful information. An outer join retains
the information that would have been lost from the tables, replacing missing
data with nulls.
There are three forms of the outer join, depending on which data is to be kept.
JOIN example 2
From the example, one can see that for complicated cases a large amount of
the answer is formed from operator names, such as PROJECT and JOIN. It is
therefore commonplace to use symbolic notation to represent the operators.
Usage
The symbolic operators are used as with the verbal ones. So, to find all
employees in department 1:
SELECTdepno = 1(employee)
becomes ódepno = 1(employee)
Conditions can be combined together using ^ (AND) and v (OR). For example,
all employees in department 1 called ‘URS’:
Rename Operator
Ñemp2.surname,emp2.forenames (
óemployee.empno = 3 ^ employee.depno = emp2.depno (
employee × (ñemp2employee) ) )
Derivable Operators
Equivalences
A ×B Ô! B × A
A )” B Ô! B )” A
A *”B Ô! B *” A
ða1(A) Ô! ða1(ða1,etc(A))
When any query is submitted to the DBMS, its query ptimizat tries to find the
most efficient equivalent expression before evaluating it.
were able to bring in data from a range of different data sources, such as,
mainframe computer, minicomputer, as well as personal computer and office
automation software such as spreadsheets and integrate this information in a
single place. This capability, coupled with user-friendly reporting tools, and
freedom from operational impacts has led to a growth of this type of computer
system.
Data ware house have evolved though several fundamental stages like:
Offline operational databases – Data warehouse in this initial stage are developed
by simply copying the database of an operational system to an off-line server
where the processing load of reporting does not impact on the operational
system’s performance.
Data Sources: Data sources refer to any electronic repository of information that
contains data of interest for management use or analytics. From mainframe(IBM
DB2,ISAM,Adabas, etc.), client-server databases (e.g Oracle database, Informix,
Microsoft SQL Server etc.,), PC databases (e.g Microsoft Access), and ESS and
other electronic store of data. Data needs to be passed from these to systems to
the data warehouse either on the transaction-by-transaction basis for real-time
data warehouses or on a regular cycle(e.g daily or weekly) for offline data
warehouses.
Data transformation: The data transformation layer receives data from the data
sources, cleaned and standardizes and loads it into the data repository. This is
often called “staging” data as data often passes through a temporary database
whilst it is being transformed. This activity of transformation data can be
performed either by manually created code or a specific type of software could
be used called an Extract, Transform and load(ETL) tool.
Data Concepts 329
Metadata: Metadata or “Data about data” is used to inform operators and uses of
the data warehouses about its status and the information held within the data
warehouses.
Data mining analysis tends to work form the data up and the best techniques
are those developed with an orientation towards large volumes of data, making
use of as much of the collected data as possible to arrive at reliable conclusions
and decisions.
330 Data Concepts
The analysis process starts with a set of data, uses a methodology to develop an
optimal representation to the structure of the data during which time knowledge
is acquired. Once knowledge has been acquired this can be extended to larger
sets of data working on the assumption that the larger data set has a structure
similar to the sample data. Again this is analogous to a mining operation where
large amounts of low grade materials are sifted through in order to find something
of value.
Some of the data mining software’s are SPSS, SAS, Think Analytics and G-Sat
etc.
The phases start with the raw data and finish with the extracted knowledge
which was acquired as a result of the following stages:
Selection- Selecting or segmenting the data according to some criteria e.g. all
those people who won a car, in this way subsets of the data can be determined.
Preprocessing – This is the data cleaning stage where certain information is
removed which deemed unnecessary and may slow down queries for e.g.: gender
of the patient. The data is reconfigured to ensure a consistent format as there is
a possibility of inconsistent formats because the data is drawn from several
sources e.g. gender may be recorded as F or M also as 1 or 0.
Transformation – The data is not merely transferred, but transformed. E.g.:
demographic overlays commonly used in market research. The data is made
useable and navigable.
Data mining- This stage is concerned with the extraction of patterns from the
data. A pattern can be defined as given a set of facts(data) F, a language L, and
some measure of certainty C a pattern is a statement S in L that describes
relationships among a subset Fs of F with a certainly c such that S is simpler in
some sense than the enumeration of all the facts in Fs.
Interpretation and Evaluation – The patterns identified by the system are
interpreted into knowledge which can be used to support human decision-making
e.g. prediction and classification tasks, summarizing the content of a database
or explaining observed phenomena.
Summary
> The basic concepts of database that can be used by various users to store
and retrieve thae data in standardized format.
> DBMS features, parts,problems and solutions.
>Three database structures.
> Enitity relations.
> Various relationships.
> Keys
> Database warehouse, Data mining