Uploaded by Dee Stha

C Tutorial Sheet

advertisement
Hand Out
Chapter 1: Introduction to Object Oriented Approach
OOP Approach
Chapter 1 Object Oriented Programming Approach
The term Object Oriented programming is frequently heard in the programming
arena. Object oriented approach was started to overcome the limitations of the
earlier programming approaches. It is popularly known by its acronym OOP. It is
used to develop reliable and reusable software.
The programming technology is continuously developing since the start of the
computer and related technologies. New tools and techniques are included in
programming in each phase of their development. Such enhancements increased
complexity in programming and design of large software. Similarly, the users'
requirements change and increase after the software is brought into operation. The
software may need maintenance and enhancements after the regular feedback from
the users. There could be problems to represent real life entities of problem while
analyzing and designing system. While improving the software work may need to
begin from the scratch that may increase software cost too. To incorporate users'
demands and enhancements in software with such complex systems was difficult.
To overcome such problems software developers were forced to develop new
programming method. OOP was introduced to solve such programming problems.
1.1 Software Evolution
The software evolution occurred in several phases. Since the beginning of the first
computer, programming for the computer started to develop software. The earlier
electronic computer ENIAC was programmed in machine language by using
switches to enter 1 and 0.
1.2 Basic of Object Oriented Programming
Objects are the entities that can be uniquely identified from others. They have their
unique identity and found everywhere. In real world system everything exists in
the form of objects. For example desk, bench, blackboard, student, teacher, car,
tree are objects. Every object has two things, firstly its properties we call attributes
and second its behavior we call function. For example a car is an object. It has
attributes like color, number of seats, chassis number, engine number etc and
behavior like move, stop, accelerate, turn etc. The Object Oriented Programming is
developed to model such real world system. Its sole objective is to overcome the
limitation of Procedure Oriented approach. Before discussing various features of
Object Oriented Programming, it is wise to discuss characteristics of Procedure
Programming and its limitations.
1.2.1 Procedure Oriented Programming
In procedure oriented programming a large program is broken down into smaller
manageable parts called procedures or functions. In procedure oriented
programming priority is given on function rather than data.
In procedure oriented programming language, a program basically consists of
sequence of instructions each of which tells the computer to do something such as
reading inputs from the user, doing necessary calculation, displaying output. When
a program becomes larger, it is then broken into smaller units called procedure or
functions. A number of functions are supposed to be written to accomplish such
tasks. The primary focus of procedural oriented programming is on functions
rather than data. These functions do not let code duplication. This technique is only
suitable for medium sized software applications.
The procedure oriented programming can be diagrammatically represented as
follows:
In procedure oriented programming two types of data local and global are used.
Data within the function are called local data and the data which are not within any
function are called global data. Global data are accessible to the only function
where it is declared. So each function may access its local data as well as global
data. The local data of one function is not accessible to other functions. If any data
is to be accessed by two or more functions it should be made global. However,
global data are vulnerable to another programmer to be changed unknowingly.
Functions are action oriented and do not correspond to the element of the problem.
The separate arrangement of data and functions does a poor job of modeling things
in the real world. That’s why procedure oriented programming approach does not
model real world system perfectly.
High Level Programming Languages like COBOL, FORTRAN, Pascal, C are
common procedure oriented programming languages.
1.2.1.1 Characteristics
▪
The characteristics of procedure oriented programming are listed as follows:
A large program is broken down into small manageable procedures or functions.
▪
Procedure oriented programming focuses on procedure or function rather than data.
▪
For sharing a common data among different functions the data is made global.
▪
Since global data are transferred from function to function; during the course of
transformation the global data may be altered by the function.
▪
The program design of procedure oriented programming follows top down
methodology.
1.2.1.2 Limitation
▪
Even though procedure oriented programming approach is still used in software
industry it has following limitations.
Focus on functions rather than data.
▪
In large program, it is difficult to identify belonging of global data.
▪
The use of global data is error prone and it could be an obstacle in code
maintenance and enhancements.
▪
The modification of global data requires the modification of those functions using
it.
▪
Maintaining and enhancing program code is still difficult because of global data.
▪
It does not model real world problem very well. Since functions are action oriented
and do not really correspond to the elements of problem.
1.2.2 Object oriented programming
The errors faced in the procedure oriented programming approach are the
motivating factor in the invention of objected oriented approach. In OOP, data are
treated as a critical element in the program and restricts freely transformation of
data around the system. Instead, data are associated with functions that operate on
it and protect it from accidental modification outside functions. OOP approach
permits decomposition of a problem into entities called objects and then build data
and function around them. Data of an object are accessible only by the function
belonging with the object. But function of one object may access the function of
another object.
Object-Oriented programming is a programming methodology that associates data
structures with a set of operators which act upon it. In OOP, an instance of such an
entity is known as object. In other words, OOP is a method of implementation in
which programs are organized as co-operative collections of objects, each of which
represents an instance of some class and whose classes are all members of a
hierarchy of classes united through the property called inheritance.
1.2.2.1 Characteristics
▪
OOP is most sophisticated programming methodology among other methodologies
by far. Some noticeable characteristics of OOP are as follows:
Emphasis is on data rather than procedures.
▪
Programs are divided into objects.
▪
Function and data are tied together in a single unit.
▪
Data can be hidden to prevent from accidental alteration from other function or
objects.
▪
Data access is done through the visible functions so that communication between
objects is possible.
▪
Data structures are modeled as objects.
▪
Follows Bottom up approach of program design methodology.
1.2.3 Procedure oriented versus Object oriented programming
The differences between procedural and Object oriented programming are
tabulated below:
1.3 Features of Object Oriented programming
Different features of object oriented programming are explained here.
1.3.1 Object
Objects are the entities in an object oriented system through which we perceive the
world around us. We naturally see our environment as being composed of things
which have recognizable identities & behavior. The entities are then represented as
objects in the program. They may represent a person, a place, a bank account, or
any item that the program must handle. For example Automobiles are objects as
they have size, weight, color etc as attributes (that is data) and starting, pressing the
brake, turning the wheel, pressing accelerator pedal etc as operation (that is
functions).
.
Following are some of the examples of objects in different scenario.
a) Physical Objects
· Bus in Traffic System
· Atom in chemical composition
· Diode in electronic system
· Humidity in metrological system
· Leader in political syste
b) Graphical User Interface
· Menu
· Button
· Toolbar
· Combo box
· Text box
· Windows
c) Data Structure
· Vector
· Stack
· Queue
· Tree
· Graph
d) Discipline of Human
· Actor
· Singer
· Musician
· Student
· Teacher
e) Geometrical Shapes
· Point
· Line
· Triangle
· Circle
· Ellipse
f) User defined data
· Distance
· Currency
· Time
· Date
· Complex Number
In computer programming, all these objects of the real world can be modeled by
combining data and function together to make object of the program which is not
possible in procedure oriented programming.
1.3.2 Class
Object consists of data and function tied together in a single unit. Functions are
used to manipulate on the data. The entire construct of objects can be represented
by a user defined data type in programming. The class is the user defined data type
used to declare the objects. Actually objects are the variable of the user defined
data type implemented as class. Once a class is defined, we can create any number
of objects of its type. Each object that is created from the user defined type
implemented as class is associated with the data type of that class. For example,
manager, peon, secretary clerk are the objects of the class employee. Similarly, car,
bus, jeep, truck are the objects of the class vehicle. Classes are user defined data
type (like a struct in C programming language) and behave much like built in data
type (like int, char, float) of programming language. It specifies what data and
functions will be included in objects of that class. Defining class doesn�t create
an object; however defining process specifies the data and function to be in the
objects of its type.
One of the objects of student can have following values
Name = “Bishal”
Registration_number = 200876255
Marks = {66, 77, 51, 48, 82}
The function Sort_name () will sort and display list of students on the basis of
name in alphabetical order. Similarly, function Tot_marks () will sum the marks
obtained by the student. The function Percentage_marks() will calculate the
percentage and the Decide_division () function will decide division based on
percentage obtained by the student.
▪
Each class describes a possibly infinite set of individual objects, each object is said
to be an instance of its class and each instance of the class has its own value for
each attribute but shares the attribute name and operations with other instances of
the class. The following points give the idea of class:
A class is a template that specifies data and their operations.
▪
A class is an abstraction of the real world entities with similar properties.
▪
Ideally, the class is an implementation of abstract data type.
1.3.3 Abstraction
Abstraction is representing essential features of an object without including the
background details or explanation. It focuses the outside view of an object,
separating its essential behavior from its implementation.
We can manage complexity through abstraction. Let’s take an example of vehicle.
It is constructed from thousands of parts. The abstraction allows the driver of the
vehicle to drive without having detail knowledge of the complexity of the parts.
The driver can drive the whole vehicle treating like a single object.
Similarly Operating System like Windows, UNIX provides abstraction to the user.
The user can view his files and folders without knowing internal detail of Hard
disk like the sector number, track number, cylinder number or head number.
Operating System hides the truth about the disk hardware and presents a simple
file-oriented interface.
The class is a construct in object oriented programming for creating user-defined
data for abstraction. When data and it operation are presented together, the
construct is call ADT (Abstract Data Type). In OOP classes are used in creating
ADT. For example, a student class can be made and can be available to be used in
programs. The programmer can implement the class in creating objects and its
manipulation without knowing its implementation. The program can use the
function Sort_name() to sort the names in alphabetical order without knowing
whether the implementation uses bubble sort, merge sort, quick sort algorithms.
1.3.4 Encapsulation
The mechanism of wrapping up of data and function into a single unit is called
encapsulation. Because of encapsulation data and its manipulating function can be
kept together. We can assume encapsulation as a protective wrapper that prevents
the data being accessed by other code defined outside the wrapper. By making use
of encapsulation we can easily achieve abstraction.
The purpose of a class is to encapsulate complexity. Each data or function in a
class can be marked as private or public. The public interface of a class represents
everything that external users of the class may know about the data and function.
The private function and data can only be accessed by code that is a member of a
class. The code other than member of a class cannot access a private function or
data. This insulation of data from direct access by the program is called data
hiding. After hiding data by making them private, it then safe from accidental
alteration.
The public interface should be carefully designed no to expose too much of the
inner working of a class.
1.3.5 Inheritance
Inheritance is the process by which objects of one class acquire the characteristics
of object of another class. We can use additional features to an existing class
without modifying it. This is possible by deriving a new class (derived class) from
the existing one (base class).This process of deriving a new class from the existing
base class is called inheritance.
It provides the concept of hierarchical classification. It allows the extension and
reuse of existing code without having to rewrite the existing code. We naturally
view the whole world is made up of objects. Many objects are related to each other
in a hierarchical way, such as vehicle, four wheeler, and car. If we describe vehicle
in an abstract way, the attributes may be such as color, number of seats etc. All
vehicles have common behavioral aspect like; they move, accelerate, turn and stop.
The more specific class of vehicle is four wheeler that acquires all features of class
vehicle and has more specific attributes like engine number, chases number etc.
The class vehicle is called base class (or super class) and class four wheeler is
called derives class (or subclass).
1.3.6 Reusability
Like library functions in procedural programming a class in Object Oriented
Programming can be distributed for further use. In OOP, the concept of inheritance
provides the idea of reusability. Once a class is completed and tested, it can be
distributed for the development other programs too. The programmer can add new
features or make some changes or can derive new classes from the existing class.
This idea saves time and effort of a programmer. The testing of software will
become easier as the already tested class should not be tested again. Suppose we
have got a tested class Employee and we have to design a new class for Manager.
The class Manager has all common features to class Employee. We can add some
more features to class Manager using all features of class Employee.
If a software company creates generic classes for one project then the company can
use the same class and its extensions in the new project with less time, effort and
investment.
1.3.7 Polymorphism
Polymorphism means ‘having many forms’. The polymorphism allows different
objects to respond to the same operation in different ways, the response being
specific to the type of object. The different ways of using same function or
operator depending on what they are operating on is called polymorphism.
Example of polymorphism in OOP is operator overloading, function overloading.
Still another type of polymorphism exist which is achieved at run time also called
dynamic binding.
For example operator symbol ‘+’ is used for arithmetic operation between two
numbers, however by overloading (means given additional job) it can be used over
Complex Object like currency that has Rs and Paisa as its attributes, complex
number that has real part and imaginary part as attributes. By overloading same
operator ‘+’ can be used for different purpose like concatenation of strings.
When same function name is used in defining different function to operate on
different data (type or number of data) then this feature of polymorphism is
function overloading.
1.3.8 Dynamic binding
The linking of a function call to the code to be executed in response to the call is
called binding. There are two types of binding one is static binding( also called
early binding) and another is dynamic binding( also called late binding). Function
overloading and operator overloading construct in OOP are the examples of early
binding. The early binding occurs at the compile time. This type of polymorphism
occurring at compile time is called compile time polymorphism.
Dynamic binding means that the code associated with a given function call is not
known until the time of the call at run time. It is achieved at run time so called as
run time polymorphism. Dynamic binding is possible only when we use
inheritance and access the objects through pointers. If classes Circle, Box, and
Triangle are derived from same function draw(). During the function call draw()
through the pointer variable an appropriate function belonging to that class is
involved.
1.3.9 Message passing
Procedural programming languages have function driven communication. That is a
function is invoked for a piece of data. Object oriented language have message
driven communication. A message is sent to an object. Communications among the
objects are analogous to exchanging messages among people.
An Object-Oriented program consists of set of objects that communicate with each
other. Object communicates with each other by sending and receiving message
(information). A message for an object is a request for execution of a procedure
and therefore will invoke a function or procedure in receiving object that generate
the desired result. Message passing involves specifying the name of the object
name of the function (message) and the information (arguments to function) to be
sent. In word, the message for an object is a request for the execution of a function
belonging to an object which generates the desired result for the given argument.
student.fee (name) ;
object message information
Communication between the objects takes place as long as their existence. Objects
are created and destroyed automatically whenever needed. In above example
student is regarded as an object sending the message fee to find the fee to be paid
by the student with the given name.
1.4 Popular Object oriented languages
An object-oriented programming language is one that follows object-oriented
programming techniques such as encapsulation, inheritance, polymorphism.
Simula (1967) is generally accepted as the first language to have the primary
features of an object-oriented language. It was created for making simulation
programs, in which objects were the most important information to be represented.
In around 1972 to 1980, a pure object-oriented programming language Smalltalk
was developed. It was called pure object oriented language because everything in
them was treated as objects.
It was designed specifically to facilitate and enforce Object Oriented methods.
Some languages like Java, Python were designed mainly for Object Oriented
programming along with some procedural elements.
Apart from this, some languages like C++, Perl are historically procedural
languages, but have been extended with some Object Oriented features.
Besides these, there are some languages that support abstract data type but not all
features of object-oriented programming. They are called object-based languages.
Examples of such language are Modula-2, Pliant, Ada.
1.4.1 Smalltalk
Smalltalk is an object-oriented, dynamically typed, reflective programming
language The development of Smalltalk language started in 1969 and it was
publicly available in 1980. This language was developed by Alen Kay, Dan
Ingalls, Adele, Goldberg at Xerox Palo Alto Research center (PARC). This
language is 100% Object Oriented. The development of this language is influenced
by language like Lisp, Simula, Logo, and Sketchpad. ANSI Smalltalk was ratified
in 1998 and represents the standard version of Smalltalk.
In smalltalk, objects are called instance variables. All objects are dynamic. It offers
fully automatic garbage collection and deallocation is performed by a built in
garbage collector. All variables are untyped and can hold objects of any class. New
objects are created using the same message passing mechanism used for operations
on objects. All attributes are private to the class where as all operations are public.
The syntax is very unusual and this leads to learning difficulties for programmers
who are used to conventional language syntax.
Inheritance can be achieved by supplying the name of the super class. All attributes
of super class are available to all its descendants. All methods can be overridden.
Also multiple inheritance is not supported by standard implementation of
Smalltalk. Rapid development of program is possible under its highly interactive
environment.
Example Program of Smalltalk:
Transcript show: 'Hello, world!'
In the above code, the message 'show:' is sent to the object 'Transcript' with the
String literal 'Hello, world!' as its argument. Invocation of the 'show:' method
causes the characters of its argument (the String literal 'Hello, world!') to be
displayed in the transcript ('terminal') window.
1.4.2 Eiffel
Eiffel was designed by a Bertrand Meyer in the late 1980's from France. It was
developed by Bertrand and Eiffel Software. Eiffel is an ISO-standardized objectoriented programming language designed for extensibility, reusability, and
reliability and programmer productivity. Eiffel is used in academic institutions as a
language for teaching computer-programming principles. Eiffel is used in the
finance, aerospace, health-care, video-gaming, and other industries as a
development platform. Since 1985, many suppliers have developed Eiffel
programming environments. The Eiffel language is influenced by Ada, Simula, Z
etc.
In Eiffel, there is automatic memory management, typically implemented by
garbage collection. The multiple inheritance is supported and there are mechanisms
to make inheritance safe. Provides generic programming, constrained and
unconstrained. In Eiffel every data type is based on class. It has keyword-based
syntax as in the ALGOL/Pascal tradition but separator-free (semicolon is optional),
operator syntax is available for routines. This language is case insensitivity and the
syntax is very elegant and simple has fewer reserved keywords.
The compiler normally generates C source which is than compiled using C
compiler which can lead long compile time. All Eiffel object are created on the
heap storage. It is not a popular language for mainstream application development.
Example Program of Eiffel:
class
HELLO_WORLD
create
make
feature
make
do
print ("Hello, world!")
end
end
1.4.3 Java
Java was designed by SUN (Stanford University Net) Microsystems, released in
1996 and is a pure object oriented language. The SUN says "Java is a new, simple,
object oriented, distributed, portable, architecture natural, robust, secure, multithreaded, interpreted, and high performance programming language".
It took 18 months to develop the first working version. Java was initially called
"Oak". It was renamed Java in 1995. The objective of Java was "Write Once, Run
Anywhere" (WORA). It was fairly secure and its security was configurable,
allowing network and file access to be restricted. Major web browsers soon
incorporated the ability to run secure Java applets within web pages. Java became
popular quickly. With the advent of Java 2, new versions had multiple
configurations built for different types of platforms. For example, J2EE was for
enterprise applications and the greatly stripped down version J2ME was for mobile
applications. J2SE was the designation for the Standard Edition. In 2006, for
marketing purposes, new J2 versions were renamed Java EE, Java ME, and Java
SE, respectively.
In 1997, Sun Microsystems approached the ISO/IEC JTC1 standards body and
later the Ecma International to formalize Java, but it soon withdrew from the
process. Java remains a de facto standard that is controlled through the Java
Community Process. At one time, Sun made most of its Java implementations
available without charge although they were proprietary software. Sun's revenue
from Java was generated by the selling of licenses for specialized products such as
the Java Enterprise System. Sun distinguishes between its Software Development
Kit (SDK) and Runtime Environment (JRE) which is a subset of the SDK, the
primary distinction being that in the JRE, the compiler, utility programs, and many
necessary header files are not present.
On 13 November 2006, Sun released much of Java as free software under the terms
of the GNU General Public License (GPL). On 8 May 2007 Sun finished the
process, making all of Java core code open source, aside from a small portion of
code to which Sun did not hold the copyright.
The language derives much of its syntax from C and C++ but has a simpler object
model and fewer low-level facilities. Java applications are typically compiled to
bytecode which can run on any Java virtual machine (JVM) regardless of computer
architecture.
One characteristic, platform independence, means that programs written in the Java
language must run similarly on any supported hardware/operating-system platform.
One should be able to write a program once, compile it once, and run it
anywhere.This is achieved by most Java compilers by compiling the Java language
code halfway (to Java bytecode) which means simplified machine instructions
specific to the Java platform. The code is then run on a virtual machine (VM), a
program written in native code on the host hardware that interprets and executes
generic Java bytecode. Further, standardized libraries are provided to allow access
to features of the host machines (such as graphics, threading and networking) in
unified ways. Note that, although there is an explicit compiling stage, at some
point, the Java bytecode is interpreted or converted to native machine code by the
JIT ( Just In Time) compiler.
Example Program of Java:
// Hello.java
public class Hello {
public static void main(String[] args) {
System.out.println("Hello World!");
}
}
1.4.4 C#
C# is an object-oriented programming language developed by Microsoft as part of
the .NET fromework and later approved as a standard by ECMA and ISO. Anders
Hejlsberg leads development of the C# language, which has a procedural, objectoriented syntax based on C++ and includes aspects of several other programming
languages most notably Delphi and Java with an emphasis on simplification. It was
develop by Microsoft in 2000 and was standarderised by ECMA (European
Computer Manufactor Association) in 2003.
Example Program of C#:
class ExampleClass
{
static void Main()
{
System.Console.WriteLine("Hello, world!");
}
}
1.4.5 D
The D programming language, also known simply as D, is an object-oriented,
imperative, multiparadigm system programming language by Walter Bright of
Digital Mars. It originated as a re-engineering of C++, but even though it is
predominantly influenced by that language, it is not a variant of C++. D has
redesigned some C++ features and has been influenced by concepts used in other
programming languages, such as Java, C# and Eiffel. A stable version, 1.0, was
released on January 2, 2007. An experimental version, 2.0, was released on June
17, 2007.
D is being designed with lessons learned from practical C++ usage rather than
from a theoretical perspective. Even though it uses many C/C++ concepts it also
discards some, and as such is not strictly backward compatible with C/C++ source
code. It adds to the functionality of C++ by also implementing design by contract,
unit testing, true modules, automatic memory management (garbage collection),
first class arrays, associative arrays, dynamic arrays, array slicing, nested
functions, inner classes, closures, anonymous functions, compile time function
execution, lazy evaluation and has a reengineered template syntax. D retains C++'s
ability to do low-level coding, and adds to it with support for an integrated inline
assembler. C++ multiple inheritance is replaced by Java style single inheritance
with interfaces and mixins. D's declaration, statement and expression syntax
closely matches that of C++.
Example Program of D:
import std.stdio: writefln;
void main(string[] args) {
writefln(" Hello, World!");
}
1.4.6 C++
The programming language C++ was developed by Bjarne Stroustrup at Bell Lab
in New Jersey in early 1980 s as extension of C. He named ‘C with Classes’. In
1983 it was renamed to C++. The operator ++ meaning that increment in C. ++ is
increment operator in C/C++.Enhancements started with the addition of classes,
followed by, among other features, virtual functions, operator overloading,
multiple inheritance, templates, and exception handling. The C++ programming
language standard was ratified in 1998 as ISO/IEC 14882:1998, the current version
of which is the 2003 version, ISO/IEC 14882:2003. A new version of the standard
known informally as C++0x is being developed
C++ is a general-purpose programming language. C++ is regarded as a mid-level
language, as it comprises a combination of both high-level and low-level language
features. It is a statically typed, free-form, multi-paradigm, usually compiled
language supporting procedural programming, data abstraction, object-oriented
programming, and generic programming. The C++ language corrects most of the
deficiencies of C by offering improved compile time type checking and support for
modular and object oriented programming. C++ supports multiple inheritance and
does not have garbage collector dynamically created object must be destroyed
explicitly.
Example Program of C++:
#include <iostream>
using namespace std;
int main()
{
cout<<’Hello, World!’);
return 0;
}
1.5 Advantages of OOP
Object oriented programming contributes greater programmer productivity, better
quality of software and lesser maintenance cost. The main advantages are:
· Redundant code is eliminated by various techniques like inheritance templates.
· Through data hiding, programmer can build secure programs that cannot be
invaded by code in other pats of the program.
· Existing classes can serve as library class for further enhancements. Classes are
also available as library class in the standard library of the language.
· Because of division of program into objects makes software development easy.
· Software complexity is less severe than conventional programming techniques.
· Because of dynamic binding, addition of new classes of objects at run time is
possible without modifying the existing code.
· The limitation realized in base class can be fulfilled in derived class without
writing even a single piece of code in the base class.
· Upgrading and maintenance of software is easily manageable.
· System can be easily upgraded from small to large systems.
· Message passing technique makes the interface simpler with external systems.
· Models real world system perfectly.
· Code reusability is much easier than conventional programming languages.
1.6 Disadvantages of OOP
▪
Compiler and runtime overhead. Object oriented program required greater
processing overhead demands more resources.
An object's natural environment is in RAM as a dynamic entity but traditional data
storage in files or databases
▪
Re-orientation of software developer to object-oriented thinking.
▪
Requires the mastery in software engineering and programming methodology.
▪
Benefits only in long run while managing large software projects.
▪
The message passing between many objects in a complex application can be
difficult to trace & debug.
Lab Sheets:
Lab Sheet 1
Lab Sheet 1
Review exercises in C programming
1. Write a program to find the average expenditure of a company for each month of
each year, each year and average over the range of years specified. Use arrays to
construct a table, display the table of expenditure and find the sum and average.
2. Write a program to find the position of the character 'C' in the sentence "idea
without execution is worthless" using pointer and string.
3. Store and retrieve the name of the students and obtained marks in c programming in
1st semester using structure.
4. Write a program to read name, rollno, address, and phone number of each student
in your class using structure. Store the information in file so that you can recover the
information later. While recovering the information from the file sort the information
alphabetically according to the name.
Lab Sheet 2
Lab Sheet 2
Additional Features in C++
Manipulators
Manipulators are operators that are used to format the data display. The most
commonly used manipulators are endl and setw. The endl manipulator, when used in
an output statement, causes a linefeed to be inserted. It has same effect as using the
newline character "\n" in C. For example
...
cout<< "LODGING" <<lexp<<endl;
cout<< "CLOTHING" <<cexp<<endl;
cout<< "TRAVELING" <<texp<<endl;
.....
If we assume that values of variable lexp, cexp and texp are 2000, 800 and 2500
respectively, then output appears is
LODGING 2000
CLOTHING 800
TRAVELING 2500
It is not the ideal output. setw(n) manipulator eliminate this problem by specifying
filed width. The value is right justified within field. For example
...
cout<<setw(11)<< "LODGING" <<setw(8)<<lexp<<endl;
cout<<setw(11)<< "CLOTHING" <<setw(8)<<cexp<<endl;
cout<<setw(11)<< "TRAVELING" <<setw(8)<<texp<<endl;
.....
output of this section is
LODGING 2000
CLOTHING 800
TRAVELING 2500
Namespace
The namespace feature in C++ allow us to specify a scope with a name, that is,
namespace is a named scope. The namespace feature help us to reduce the problem of
polluting the namespace. Namespace is defined as follows.
namespace nsn
{
int item;
void showitem(int it)
{
cout<<it;
}
}
The elements from the namespace are used as
cout<<nsn::item;
or it can be accessed by including the particular element as
using nsn::item;
after inclusion the statements
cout<<item; //correct
showitem(item); //not correct
We can also include every thing from the namespace as
using namespace nsn;
After this inclusion every element from the namespace can be used directly as
cout<<item;
showitem(item);
Pass by reference
When an address of the variable/object is passed, the function works directly on the
actual variable/object used in the call. This means that any changes made to the
variable/object inside the function will reflect in actual variable/object. For example
return_type function_name(datatype &, datatype &)
Return by reference
The primary reason of returning the value by reference is to use a function call on the
leftside of the equal sign. For example
max(a,b)=-1
Here the function should return reference to variables, but not the values, then the
function call will yield a reference to either a or b depending on their values.
Structure with function
The value of structure variable can be passed as a parameter to a function. For
example
struct stu
{
...
};
void show(stu);
Overloaded function
Overloaded function appears to perform different operation depending on the kind of
data sent to it. It performs one operation on one kind of data but another operation on
a different kind. The reason behind using the overloaded function is because of its
convenience to use the same function name for different operation.
void convert(); //takes no argument
void convert(int n); //takes one argument of type int
void convert(float,int); //takes two argument of type float and int
It uses the number of arguments, and their data types, to distinguish one function from
another.
Inline function
We know that function save memory space but take some extra time. If the functions
are short, we may put in the function directly in the line with the code in the calling
program. But the trouble with repeatedly inserting the same code is that you lose the
benefits of the program organization and clarity that come with using function. If the
function is very short, the instructions necessary to call it may take up as much space
as the instructions within the function body, so that there is not only a time penalty but
a space penalty as well. The solution to this is the inline function. This kind of
function is written like a normal function in the source file but complies into inline
code instead of into a function. Beside of this the source file remains well organized
and easy to read, since the functions are shown as a separate entity. Functions that are
very short, say one or two statements are candidates to be inlined.
inline(keyword) float(retutn type) convert(int n)
i.e
inline float convert(int n)
Here all we need is the keyword inline in the function definition.
Default Arguments
The function can be called without specifying all its arguments. This won't work on
just any function that is the function declaration must provide default values for those
arguments that can be missed.
Let us take an example
void dearg(char ='?',int=25); //declaration with default arguments
int main()
{
dearg();
dearg('<');
dearg('>',30);
return 0;
}
void dearg(char ch,int n)
{
...
}
Here the function dearg( ) takes two arguments. It is called three times from main( )
program. The first time it is called with no arguments, second time with one argument
and third time with two. The first and second provides default arguments, which will
be used if the calling function doesn't supply them. The default argument follows an
equal sign, which is placed directly after name. It is also possible to use variable
name. If one argument is missing it assumed to the last argument as we show in
second.
Exercises
Use manipulators where seems to be useful.
1. Write a program to set a structure to hold a date (mm,dd and yy), assign values
to the members of the structure and print out the values in the format
11/28/2004 by function. Pass the structure to the function
2. Write a program using the function overloading that converts feet to inches. Use
function with no argument, one argument and two arguments. Decide yourself
the types of arguments. Use pass by reference in any one of the function above.
3. Define two namespaces: Square and Cube. In both the namespaces, define an
integer variable named "num" and a function named "fun". The "fun" function
in "Square" namespace, should return the square of an integer passed as an
argument while the "fun" function in "Cube" namespace, should return the cube
of an integer passed as an argument. In the main function, set the integer
variables "num" of both the namespaces with different values. Then, compute
and print the cube of the integer variable "num" of the "Square" namespace
using the "fun" function of the "Cube" namespace and the square of the integer
variable "num" of the "Cube" namespace using the "fun" function of the
"Square" namespace.
4. Write a function that passes two temperatures by reference and sets the larger of
the two numbers to 100 by using return by reference.
5. Assume that employee will have to pay 10 percent income tax to the
government. Ask user to enter the employee salary. Use inline function to
display the net payment to the employee by the company.
6. Write a program that displays the current monthly salary of chief executive
officer, information officer, and system analyst, programmer that has been
increased by 9, 10, 12, and 12 percentages respectively in year 2010. Let us
assume that the salaries in year 2009 are
Chief executive officer Rs. 35000/m
Information officer Rs. 25000/m
System analyst Rs. 24000/m
Programmer Rs. 18000/m
Make function that takes two arguments; one salary and other increment. Use proper
default argument.
Lab Sheet 3
Lab Sheet 3
Concept of Objects and Classes
Objects
Object consists of the data and the functions that operate on the data. Object data is
usually private: no functions other than those within the same object can access it. On
the other hand, the functions within the object are usually public. They can be
accessed by the other functions in the program including the functions in the other
objects. So the function in one object can access the data in the other object through
the function of that object.
Classes
In oops. Objects are variables of classes. It is a specification for any number of objects
based on that class. Class itself is a template (data type) for objects. When we actually
define the object, of a class we are requesting to allocate memory for that object to
hold its data.
Comments in C++
In C++, a new symbol for comment '//' (double slash) is introduced and is called oneline comment.
// this is an example of comment illustration
stdno=48; //no of student in 059/bct batch
C comment symbols '/*' and '*/' are also valid and can be used for multi-line
comments.
/*this is an example illustrating the multi-line
comment in C++ */
Output Statement
The statement
cout << "This is the first lab in C++";
cause the string "This is the first lab in C++" to be displayed on the screen. Here cout
is the predefined object that represents the standard output stream in C++.
The operator '<<', insertion operator, has a simple interface, i.e it is not necessary to
specify the data type of the variable on its right. The insertion operator automatically
works with any type of the variable. Another advantage of this is that user-defined
data types can also be used with this operator, which is not possible with printf( )
function.
Input Statement
The following statement reads the value from the keyboard and places it in a variable
size.
cin >> size;
cin identifier represents the standard input device. The >> operator (extraction
operator) takes the input from the device. The function is smart enough to interpret the
input according to the data type of the variable that holds the value. If size is an
integer and the user types "25", the integer value 25 will be placed in size. If the size
is a string, the string "25" will be placed in it.
Data Member
The data items within a class are called data members. There can be any number of
data members in a class. Normally, data members follow the keyword private, so they
can be accessed from within the class but not from outside. That is why we say that
oops have feature of data hiding. So, it is safe from accidental alteration.
class demo
{
private:
int rollno; //member data
float score; //member data
public:
setdata( int rl, float sc) //member function
{rollno=rl; score=sc;}
setdata( )
{
cout<<"Enter the roll no: \n";
cin>>rollno;
cout<<"Score: \n";
cin>>score;
}
showdata( ) //member function
{
cout<<"\Roll No: " <<rollno<<"has scored "<<score<<endl;
}
};
above class contains two data items: rollno and score. Here rollno is of type int and
score is of type float.
Member Function
Member functions are functions that are included within a class. In above example
there are two member functions in class demo: setdata( ) and showdata( ). Each
function can have one or more statements. The functions setdata( ) and showdata( )
follow the keyword public which means that they can be accessed from outside the
class. It is also possible to declare a function within a class and define it elsewhere.
The class demo can be used as follows
int main()
{
demo d1,d3;
d1.setdata(12,10.4);
d3.setdata( );
d1.showdata( );
d3.showdata( );
return 0;
}
Defining the Objects
Here the d1 and d3 are defined as objects of class demo. Defining the object is
similar to defining a variable of any data type. Space is set-aside for it. Defining the
object is creating them i.e instance of the class is created. In general objects in the
programs represent physical objects: things that can be felt or seen, for example circle,
person, car etc
Calling Member
Functions
Member functions are called as follows
d1.setdata(12,10.4);
d3.setdata( );
d1.showdata( );
d3.showdata( );
This syntax is used to call a member function that is associated with a specific object.
Because of the demo class, it must always be called in connection with an object of
this class. Here the first member function is called by passing the values while the
second is called without passing any value.
Exercises
1. Write a simple program that convert the temperature in degree Celsius to
degree Fahrenheit and vice versa using the basic concept of class and object.
Make separate class for Centigrade and Fahrenheit which will have the private
member to hold the temperature value and make conversion functions in each
class for conversion from one to other. For example you will have function
toFahrenheit() in class Celsius that converts to Fahrenheit scale and returns the
value.
2. Assume that you want to check whether the number is prime or not. Write a
program that asks for a number repeatedly. When it finishes the calculation the
program asks if the user wants to do another calculation. The response can be
'y' or 'n'. Don't forget to use the object class concept.
3. Create a class called carpark that has int data member for car id, int data
member for charge/hour and float data member for time. Set the data and show
the charges and parked hours of corresponding car id. Make two member
functions for setting and showing the data. Member function should be called
from other functions.
4. Write a program with classes to represent circle, rectangle and triangle. Each
classes should have data members to represent the actual objects and member
functions to read and display objects, find perimeter and area of the objects and
other useful functions. Use the classes to create objects in your program.
5. Assume that an object represents an employee report that contains the
information like employee id, total bonus, total overtime in a particular year.
Use array of objects to represent n employees' reports. Write a program that
displays report. Use setpara() member function to set report attributes by
passing the arguments and member function displayreport() to show the reports
according to parameter passed. Display the report in following format.
Employee with ... ... ... has received Rs ... ... ...as bonus
and
had worked ... ... ... hours as a over time in year ... ... ...
Lab Sheet 4
Lab Sheet 4
Additional Components of a Class
Constructor
A constructor is basically a function used for initialization of the class data members, allocation of
memory, and so on. It is convenient if an object can initialize itself when it is first created, without
the need to make a separate call to a member function. It has the same name as the class in which
they are members. No return type is used for constructors. Since the constructor is called
automatically by the system there is no reason for it to return anything. Compiler knows that they are
constructors by looking at their name and return type. Let us take an example that each time an object
of the date class is created, it is to be initialized with the date 2/02/2011.
Examples:
class date{
private:
int dd,yy;
char mm[3];
public:
date() // constructor
{ dd=2,mm[0]='0',mm[1]='2';
mm[2]='\0', yy=2011;
}
showdate() //display
{
cout<<"\n"<<dd<<"/"<<mm<<"/"<<yy;
}
};
int main()
{
date d1; //define and initialize
clrscr();
d1.showdate();
return 0;
}
Here as soon as an object d1 is created, the constructor will be involved and the values dd, mm, and
yy initialized to the required date- 2/02/2011. Note that the constructor here neither takes any
parameters nor does it return values. So it is called default constructor. Data members of object can
be initialized by passing arguments to the constructor when the object is created. The constructor that
takes arguments is called parameterized constructor. Following example adds parameterized
constructor in the above example program.
class date{
//....
public:
date() // constructor
{ dd=2,mm[0]='0',mm[1]='2';
mm[2]='\0', yy=2011;
}
date(int d, char m[], int y) //parameterized constructor
{ dd=d,mm[0]=m[0],mm[1]=m[1];
mm[2]='\0', yy=y;
}
//......
};
int main()
{
date d1(2,"02",2011); //define and initialize
d1.showdate();
return 0;
}
Copy Constructor
We already know that no argument constructor can initialize data members to constant values, and
parameterized constructor can initialize data members to values passed as arguments. There is also
another way to initialize an object with another object of the same type. It is called the default copy
constructor. It is a one-argument constructor whose argument is an object of same class.
Example:
class date
{
private:
int dd,yy;
int mm;
public:
date()
{ dd=26, mm=1,yy=2004; }
date(int ee,int nn,int zz): dd(ee),mm(nn),yy(zz) //parameterized Constructor
{}
showdate()
{ cout<<"\n"<<dd<<"/"<<mm<<"/"<<yy;}
};
int main()
{
date d1(26,2,2004);
date d2(d1); //copy constructor call: it can also be written as date d2=d1;
d1.showdate();
d2.showdate();
return 0;
}
Destructor
Constructors serve to automatically initialize data members of an object at the point of creation.
Destructors are complimentary to constructors. They serve to cleanup objects when they are
destroyed.
A destructor may be called either when the object goes out of scope or when it is destroyed explicitly
using the delete operator. A destructor, like a constructor has the same name as that of the class, but
is prefixed by the tilde ('~') symbol. A class cannot have more than one destructor. And destructor
can't take arguments or specify a return value. The most common use of destructor is to de-allocate
memory that was allocated for the object by the constructor. Destructor for above program is
~date() //destructor
{}
Constant Member Function
A function is made a constant function by placing the keyword const after the function header before
function body. Member function that do not change the value of its object but acquire data from their
object are obvious candidates for constant function.
General syntax:
return_type func_name(argument list) const; //const function declaration
//.....
return_type func_name(argument list) const //const function definition
{
//Function body;
}
Constant Object
When an object is declared as constant, we can't modify it. The constant objects can only use
constant member functions with it, because they are the only ones that guarantee not to modify its
value.
General syntax:
const class_name object_name; //creation of constant object
Constant Reference Argument
When we don't want to modify the arguments passed to the function, the reference parameters are
made const in the function declaration and definition.
General syntax:
return_type func_name(const int&, float&); //function declaration with const member function
arguments
//......
return_type func_name(const int&, float&) //function definition with const member function
arguments
{
//function body; //here int type can't be modify but float can be.
}
Static Data Members
If a data item in class is declared as static, then only one copy of that item is created for the entire
class, no matter how many objects there are. All the objects share a common item of information.
Once the first object is created its value is initialized to zero. And separate definition for static data
member is necessary outside the class
General syntax:
class class_name
{
//......
static data_type variable_name; //declaration of static data member inside the class
//.....
};
data_type class_name :: variable_name; //definition of static data member outside the class and here
value can
//be assign to variable.
Static Member Function
A static member function can have access to only other static members declared in the same class
and it can be called using the class name
General Syntax:
static return_type func_name (argument list); //declaration of static member function
//....
class_name:: fun_name(argument passed) // static member function call
Exercises
1. Write a program that has a class to represent time. The class should have constructors
to initialize data members hour, minute and second to 0 and to initialize them to
values passed as arguments. The class should have member function to add time
objects and return the result as time object. There should be another function to
display the result in 24 hour format.
2. Write a program that has a class with a dynamically allocated character array as its
data member. One object should contain "Engineers are" and another should contain "
Creatures of logic". Member function join() should concatenate two strings by passing
two objects as arguments. Display the concatenated string through a member function.
Use constructors to allocate and initialize the data member. Also, write a destructor to
free the allocated memory for the character array. Make your own function for
concatenation of two strings.
3. Write a class that can store Department ID and Department Name with constructors to
initialize its members. Write destructor member in the same class and display the
message "Object n goes out of the scope". Your program should be made such that it
should show the order of constructor and destructor invocation.
4. Assume that one constructor initializes data member say num_vehicle, hour and rate.
There should be 10% discount if num_vehicle exceeds 10. Display the total charge.
Use two objects and show bit-by-bit copy of one object to another (make your own
copy constructor).
5. Write a program that illustrate the following relationship and comment the
relationships.
6. i) const_object.non_const_mem_function
7. ii) const_object.const_mem_function
8. iii) non_const_object.non_const_mem_function
9. iv) non_const_object.const_mem_function
10. Create a class with a data member to hold "serial number" for each object created
from the class. That is, the first object created will be numbered 1, the second 2 and so
on by using the basic concept of static data members. Use static member function if it
is useful in any of the member functions declared in the program. Otherwise make
separate program that demonstrate the use of static member function.
Proposal Guidelines
Guidelines for Submitting Proposal
Your proposal should include:
1. Acknowledgment
2. Table of Contents
3. Introduction
4. Objectives
5. Existing System (if any)
6. Proposed System
1. Description
2. System Block Diagram
7. Methodology
8. Project Scope
9. Project Schedule
[Students can add their own topics or sub-topics as per necessity.]
Requirements:
Your proposal should be submitted in plastic-tape-binding form. The proposal should meet following
standards:
Font Name: Times New Roman
Font Size: 12 points
Paper Size: A4
Left Margin: 1.5 inch
Right Margin: 1.25 inch
Top Margin: 1 inch
Bottom Margin: 1 inch
Header and Footer: 0.5 inch
Line Spacing: 1.5
Heading should be written in following styles and points
1 Heading 1: 18 points (Bold)
1.1 Heading 2: 16 points (Bold)
1.1.1 Heading 3: 14 points (Bold)
1.1.1.1 Heading 4: 13 points (Bold)
Some previously submitted projects:
1. Elevator Control Simulation
2. Graph of Equations
3. Bingo
4. Pair Matching Game of Cards
5. Snake game with Artificial Intelligence
6. Object Oriented Typing Tutor
7. Su Do Ku
8. Brick Game
9. Billing Software
10. Game Package: Pac man, ping pong, sky invader
11. Event Coordinator
12. Graphical calculator
13. Graphical calendar with clock
14. Ticket reservation system
15. Solution of K-map
16. Management system: hotel, library etc.
17. Bagchal etc.
Group Formation:
Following rules are to be followed while forming the group:
1. Groups consisting of 2 (at least) or 3 (at most) are to be formed.
2. Students must not form project group with friends of different sections (section A and section B).
Deadline for submission of Proposal:
Respective lab time of Lab 5 of each group
Lab Sheet 5
Lab Sheet 5
Understanding the Concept of Friend Function/Class and Operator Overloading
Friend Function and Class
In some cases you need to access the private data members of a class from non member functions. In
such situations you must declare the function as friend function of the class. This friend function
seems to violate the data hiding feature of OOP concept. However, the function that accesses private
data must be declared as friend function within the class. With friend functions data integrity is still
maintained.
Sometimes you may need to make, one or all the member functions of a class friend to other class.
For that we declare class or member function as the friend to the other class so that one or all the
member functions of the declared class will be friend to the class within which it is declared.
Example:
class breadth;
class length
{
private:
......
public:
......
friend int add(length, breadth); //friend function declaration
};
class breadth
{
private:
......
public:
......
friend int add(length, breadth); //friend function declaration
};
int add( length l, breadth b) { }
Operator Overloading
We have already studied that we can make user defined data types behave in much the same way as
the built-in types. C++ also permits us to use operators with user defined types in the same way as
they are applied to the basic types. We need to represent different data items by objects and
operations on those objects by operators. Operator can be overloaded for those different operations.
Most programmers implicitly use overloaded operators regularly. For example, the addition operator
(+) operates quite differently on integers, float and doubles and other built-in types because operator
(+) has been overloaded in the C++ language itself. Operators are overloaded by writing a function
definition as you normally would, except that the function name now becomes the
keyword operator followed by the symbol for the operator being overloaded. Operator overloading
provides a flexible option for the creation of new definitions for most of the C++ operators for your
class.
Syntax
<return type> operator <operator_symbol> ( <parameters> )
{
<statements>;
}
example:
complex operator + (complex c1,complex c2)
{
return complex(c1.real+c2.real,c1.imag+c2.imag);
}
Exercises
1. Write a class for instantiating the objects that represent the two-dimensional
Cartesian coordinate system.
A. make a particular member function of one class to friend function in another class
for addition
B. make other three functions to work as a bridge between the classes for
multiplication, division and subtraction.
C. Also write a small program to demonstrate that all the member functions of one
class are the friend functions of another class if the former class is made friend to the
latter.
Make least possible classes to demonstrate all above in single program without
conflict.
2. Write a class to store x, y, and z coordinates of a point in three-dimensional space.
Using operator overloading, write friend functions to add, and subtract the vectors.
3. Compare the two object that contains integer values that demonstrate the
overloading of equality (==), less than (<), greater than (>), not equal (!=),greater than
or equal to (>=) and less than or equal to(<=) operators.
4. Write a class Date that uses pre increment and post increment operators to add 1 to
the day in the Date object, while causing appropriate increments to the month and
year (use the appropriate condition for leap year). The pre and post increment
operators in your Date class should behave exactly as the built in increment operators.
Lab Sheet 6
Lab Sheet 6
Understanding the Concept of Type Conversion and Inheritance
Type Conversion
To convert data from basic type to user defined type and vice versa we cannot rely on built in
conversion routines because compiler doesn't know anything about user defined types. We have to
provide the conversion routines to be used for type casting. Following methods are used for
conversion.
a) To convert from basic type to user defined type, conversion is done by using the constructor
function with one argument of basic type as follows
MyClass(BasicType var)
{
//Conversion code
}
b) To convert from user defined type to basic type, conversion is done by overloading the cast
operator of basic type as a member function as follows
class MyClass
{
...
Public:
operator BasicType()
{
//Conversion code
}
};
The conversions between objects of different classes can be carried out by using similar methods for
conversions between basic types and user-defined types. For more details please refer to any text
books.
Inheritance
Inheritance is the concept by which the properties of one entity are made available to another. It
allows new classes to be built from older and less specialized classes instead of being rewritten from
scratch. The class that inherits properties and functions is called the subclass or the derived class and
the class from which they are inherited is called the super class or the base class. The derived class
inherits all the properties of the base class and can add properties and refinements of its own. The
base class remains unchanged.
Example
class person //base class
{
protected:
int age;
char name[20];
public:
void readAge(void)
{
cout<<"Enter Age: ";
cin>>age;
}
void readName(void)
{
cout<<"\nEnter Name: ";
cin>>name;
}
void printPerInformation(void)
{
cout<<"Name - "<<name;
cout<<"\nAge - "<<age;
}
};
//derived class inherits base class
class student:public person
{
private:
int Sno;
int percentage;
public:
void readSno(void)
{
cout<<"Enter Sno.: "; cin>>Sno;
}
void readpercentage(void)
{
cout<<"Enter percentage: ";
cin>>percentage;
}
void printStuInformation(void)
{
cout<<"\nName - "<<name;
cout<<"\nAge - "<<age;
cout<<"\nS.no - "<<Sno<<endl;
cout<<"Percentage- "<<percentage<<endl;
cout<<"conclusion"<<endl;
if(percentage>=80)
cout<<"\nThe student is Outstanding"<<endl
else if(percentage>=70)
cout<<"The student is Medium"<<endl;
else
cout<<"The student is Poor"<<endl;
}
};
int main(void)
{
clrscr();
student st;
st.readName();
st.readAge();
st.readSno();
st.readpercentage();
st.printStuInformation();
return 0;
}
In Above example, person is the base class whereas student is the derived class which inherits all the
features of the base class. Multiple classes may be derived from same base class and a derived class
can also inherit characteristics of two or more classes.
This pointer
A special pointer called this pointer can be employed in C++ programs. When the object needs to
point to itself then this pointer is used. Remember this pointer points (or represents the address of
the) object of the class but not the class.
Example
class student:public person
{
private:
......
public:
......
void printAddress(void)
{
cout<<"I am from within the object and my address is"<<this;
}
};
Exercises
1. Write a program that can convert the Distance (meter, centimeter) to meters measurement in float
and vice versa. Make a class distance with two data members, meter and centimeter. You can add
function members as per your requirement.
2. Write two classes to store distances in meter-centimeter and feet-inch system respectively. Write
conversions functions so that the program can convert objects of both types.
3. Create a class called Musicians to contain three methods string ( ), wind ( ) and perc ( ). Each of
these methods should initialize a string array to contain the following instruments
- veena, guitar, sitar, sarod and mandolin under string ( )
- flute, clarinet saxophone, nadhaswaram and piccolo under wind ( )
- tabla, mridangam, bangos, drums and tambour under perc ( )
It should also display the contents of the arrays that are initialized. Create a derived class called
TypeIns to contain a method called get ( ) and show ( ). The get ( ) method must display a menu as
follows
Type of instruments to be displayed
a. String instruments
b. Wind instruments
c. Percussion instruments
The show ( ) method should display the relevant detail according to our choice. The base class
variables must be accessible only to its derived classes.
4. Write three derived classes inheriting functionality of base class person (should have a member
function that asks to enter name and age) and with added unique features of student, and employee,
and functionality to assign, change and delete records of student and employee. And make one
member function for printing address of the objects of classes (base and derived) using this pointer.
Create two objects of base class and derived classes each and print the addresses of individual
objects. Using calculator, calculate the address space occupied by each object and verify this with
address spaces printed by the program.
5. Write base class that ask the user to enter a complex number and make a derived class that adds
the complex number of its own with the base. Finally make third class that is friend of derived and
calculate the difference of base complex number and its own complex number.
Lab Sheet 7
Lab Sheet 7
Understanding the Concept of Virtual function, Virtual base class and RTTI
Virtual Function
The overridden function in the derived class can be invoked by means of a base class pointer if the
function is declared virtual in the base class. Suppose a virtual function get( ) is defined in the base
class Base and again it is defined in the derived class Derived.
We can use the base class pointer to invoke the get( ) function of the derived class.
Derived d;
Base *b;
b=&d;
b-> get( ) //it calls the get ( ) function of the derived class.
Virtual Destructors
When a base class pointer that is pointing to a derived class object is deleted, destructor of the
derived class as well as destructors of all its base classes is invoked, if the destructor in the base class
is declared as virtual.
Virtual Base Class
In this type of inheritance there may be ambiguity in the members of the derived class child because
it is derived from two base classes, which are again derived from the same base class. Hence to avoid
this ambiguity the class G – parent can be made virtual.
Runtime Type Information (RTTI)
The runtime type information is one of the features of C++ that exhibit runtime polymorphic
behavior. In C++ we can find the type information of an object at runtime and change the type of the
object at runtime. The operators dynamic_cast and typeid are used for runtime type information.
For example if Animal is a polymorphic base class and Dog and Cat are derived classes of base class
Animal then
Animal *anmp;
Dog dg;
Cat ct;
anmp=&dg;
cout<< typeid(*anmp).name();
displays the information of the object pointed by anm pointer
Similarly
Cat *cpt;
cpt=dynamic_cast<Cat*>(panm);
The down cast is successful if panm is holding the address of objects of class Cat.
Exercises
1. Write a program to create a class shape with functions to find area of the shapes and
display the name of the shape and other essential component of the class. Create
derived classes circle, rectangle and trapezoid each having overridden functions area
and display. Write a suitable program to illustrate virtual functions and virtual
destructor.
2. Create a class Person and two derived classes Employee, and Student, inherited from
class Person. Now create a class Manager which is derived from two base
classes Employee and Student. Show the use of the virtual base class.
3. Write a program with Student as abstract class and create derive
classes Engineering, Medicine and Science from base class Student. Create the
objects of the derived classes and process them and access them using array of pointer
of type base class Student.
4. Create
a
polymorphic
class Vehicle and
create
other
derived
classes Bus, Car and Bike from Vehicle. With this program illustrate RTTI by the use
of dynamic_cast and typeid operators.
Lab Sheet 8
Lab Sheet 8
Understanding the Concept of Console and File Input/Output
Console Input/Output
Within console we can perform unformatted and formatted input/output. For unformatted
input/output stream functions like put(), get(), getline(), write(), read() etc are used. For formatted
input/output the stream objects cin and cout are used along with ios functions and flags and
manipulators.
▪
The ios functions that can be used for formatting are
width()
▪
fill()
▪
precision()
▪
setf()
▪
unsetf()
▪
flags() etc
However to use the setf(), unsetf() and flags() functions one should know the flags available in ios
class.
File Handling
▪
There are three classes for handling files.
ifstream - for handling input files
▪
ofstream - for handling output files
▪
fstream - for handling input as well as output files.
In all three classes, passing a filename as the first parameter in the constructor itself can open a file.
e.g ifstream infile("test.txt") opens the file test.txt in the input mode.
The constructors for all these classes are defined in the header file <fstream>, which are as follows
ifstream( const char *path, int mode=ios::in)
ofstream( const char *path, int mode=ios::out)
fstream( const char *path, int mode=ios::in|ios::out)
where path specifies the file to be opened, mode specifies the mode in which the file is to be opened.
File opening can also be done explicitly by calling the member function open() of the file stream
classes. The open() function has similar prototype as the constructors.
After opening, the file contents can be written or read by using the stream operators with the file
objects as
ofstream ofile("test.txt");
ofile<<"C++ lab class";
This statement writes "C++ lab class" in the file "test.txt"
Reading and Writing A class Object
The Binary input and output functions read( ) and write are designed to handle the entire structure of
an object as a single unit, using the computer's internal representation of data. The function write
copies a class object from memory byte by byte with no conversion.
Binary output and input functions take the following form
ipfile.read(reinterpret_cast<char*>(&obj),sizeof(obj));
opfile.write(reinterpret_cast<char*>(&obj),sizeof(obj));
Example
#include<iostream>
#include<fstream>
#include<iomanip>
using namespace std;
class demofile
{
private:
int a;
int b;
public:
demofile(){}
demofile(int x,int y){a=x;b=y;}
void display()
{ cout<<"a= "<<a<<endl<<"b= "<<b<<endl;}
};
int main()
{
demofile de(10,20);
clrscr();
fstream file;
file.open("demo.txt",ios::in|ios::out);
file.write(reinterpret_cast<char*>(&de),sizeof(de));
file.seekg(0);
file.read(reinterpret_cast<char*>(&de),sizeof(de));
de.display();
file.close();
return 0;
}
Exercises
1. Write a program to demonstrate the use of different ios flags and functions to
format the output. Create a program to generate the bill invoice of a department store
by using different formatting.
2. Write a program to create a userdefined manipulator that will format the output by
setting the width, precision and fill character at the same time by passing arguments.
3. Write a program to overload stream operators to read complex number and display
the complex number in a+ib format.
4. Write a program that stores the information about students (name, student
id,department and address) in a structure and then transfers the information to a file in
your directory. Finally, retrieve the information from your file and print in the proper
format on your output screen.
5. Write a program for transaction processing that write and read object randomly to
and from a random access file so that user can add, update, delete and display the
account information (accountnumber, lastname, firstname, totalbalance).
Lab Sheet 9
Lab Sheet 9
Understanding the Concept of Templates and Exception
Function Template
Overloaded functions normally are used to perform similar operations on different types of data. If
the operations are identical for each type, it is more convenient to use function templates. The
programmer writes a single function-template definition. Based on the argument types provided
explicitly or inferred from calls to this function, the compiler generates separate object-code function
to handle each function call appropriately.
All function-template definition begin with keyword template followed by a list of formal type
parameters to the function template enclosed in angle brackets (< and >); each formal type parameter
must be preceded by either of the interchangeable keywords class or typename, as in
template< class Type >
Or
template< typename ElementType >
Or
template< class Type_1, class Type_2>
Example
#include<iostream>
using namespace std;
//function template printArray definition
template< class T>
void printArray(T *array,int count)
{
for(int i=0;i<cout;i++)
cout<<array[i]<<" "<<endl;
}
//end of the function
int main()
{
int a[4]={1,2,3,4};
double b[5]={1.1,2.2,3.3,4.4,5.5};
char c[6]= "Hello";
cout<<" Array a contains: "<<endl;
printArray(a,4);
cout<<" Array b contains: "<<endl;
printArray(b,5);
cout<<" Array c contains: "<<endl;
printArray(c,6);
return 0;
}
Class Template
The template concept can be extended to classes. Class templates are generally used for data storage
classes. The approach is similar to that used in function template. Here the template keyword and
class name signal that the entire class will be a template.
template <class T>
Class Stack
{
//data and member functions using argument T
};
Example
#include<iostream>
using namespace std;
template<class T>
class Stack
{
private:
T st[100];
int top;
public:
Stack();
void push(T var);
T pop();
};
template<class T>
void Stack<T>::Stack()
{
top=-1;
}
template<class T>
void Stack<T>::push(T var)
{
st[++top]=var;
}
template<class T>
T Stack<T>::pop()
{
return st[top--];
}
int main()
{
Stack<float> s1;
s1.push(111.1F);
s1.push(222.2F);
s1.push(333.3F);
cout<<"1 : "<<s1.pop()<<endl;
cout<<"2 : "<<s1.pop()<<endl;
cout<<"3 : "<<s1.pop()<<endl;
Stack<long> s2;
s2.push(123123123L);
s2.push(234234234L);
s2.push(345345345L);
cout<<"1 : "<<s2.pop()<<endl;
cout<<"2 : "<<s2.pop()<<endl;
cout<<"3 : "<<s2.pop()<<endl;
return 0;
}
Exception Handling
Exception handling is designed to handle only synchronous exceptions. The mechanism provides
means to detect and report an exceptional circumstance so that appropriate action can be taken. The
mechanism suggests a separate error handling code that performs the following tasks:
1. Find the problem ( Hit the exception)
2. Inform that an error has occurred( Throw the exception)
3. Receive the error information( Catch the exception)
4. Take corrective actions( Handle the exception)
General syntax
.........
try
{
..........
throw exception_object; //Block of statements which detects and throws an exception
.........
}
catch(type arg) //Catches exception
{
......... //Block of statements that handles the exception
}
.........
.........
Example
#include<iostream>
using namespace std;
class ex_demo
{
private:
int a;
int b;
public:
ex_demo(){}
class DIVIDE{}; //abstract class for exception
void getdata()
{
else
{
throw DIVIDE();
}
}
catch(DIVIDE)
{
cout<<"Exception Caught : b= " <<b<<endl;
cout<<"Enter dividend (A) and divisor (B)" <<endl;
}
}
};
int main()
{
clrscr();
ex_demo ex;
ex.getdata();
ex.divide();
return 0;
}
cin>>a>>b;
}
void divide()
{
try
{
if(b!=0)
{
cout<<"Result(A/B) = "<<a/b<<endl;
}
Multiple Catch Statement
A program can have more than one condition to throw an exception. It is possible to use multiple
catch statements with try block. When an exception is thrown, the exception handlers are searched in
order for an appropriate match. The first handler that yields a match is executed, after executing the
handler; the control goes to the first statement after the last catch block for that try.
Syntax
try
{
//try block
}
catch(type1 arg)
{
//catch block
}
catch(type2 arg)
{
//catch block
}
....
....
catch(typeN arg)
{
//catch block
}
Re-throwing an exception
A handler may decide to re-throw the exception caught without processing it. In such situation, we
may simply invoke throw without any arguments as shown below:
throw;
This cause the current exception to be thrown to the next enclosing try/catch sequence and is caught
by a catch statement listed after that enclosing try block.
Exercises
1. Create a function called sum ( ) that returns the sum of the elements of an array.
Make this function into a template so it will work with any numerical type.
Write a main ( ) program that applies this function to data of various type.
2. Write a class template for queue class. Assume the programmer using the queue
won't make mistakes, like exceeding the capacity of the queue, or trying to
remove an item when the queue is empty. Define several queues of different
data types and insert and remove data from them.
3. Modify the stack class given in the previous lab to add the exception when user
tries to add item while the stack is full and when user tries to add item while the
stack is empty. Throw exception in both of the cases and handle these
exceptions.
4. Write any program that demonstrates the use of multiple catch handling, rethrowing an exception, and catching all exception.
Report Guidelines
Guidelines for Submitting Project Report and Project Presentation
Your report should include:
1. Acknowledgment
2. Abstract
3. Table of Contents
4. Objectives
5. Introduction
6. Application
7. Literature survey
8. Existing System
9. Methodology
10. Implementation
1. Block diagram
11. Results
12. Problems Faced and solutions
13. Limitations and future enhancements
14. Conclusion and recommendations
15. References
[Students can add their own topics or sub-topics as per necessity.]
Requirements:
Your project report should be submitted in plastic-tape-binding form. The project report should meet
following standards:
Font Name: Times New Roman
Font Size: 12 points
Paper Size: A4
Left Margin: 1.5 inch
Right Margin: 1.25 inch
Top Margin: 1 inch
Bottom Margin: 1 inch
Header and Footer: 0.5 inch
Line Spacing: 1.5
Heading should be written in following styles and sizes
1 Heading 1: 18 points (Bold)
1.1 Heading 2: 16 points (Bold)
1.1.1 Heading 3: 14 points (Bold)
1.1.1.1 Heading 4: 13 points (Bold)
You should prepare presentation slides that can describe your project with in the time limit. The
presentation slides should include topics from the project report in short in concise form. Presentation
should be done in English.
Time for presentation
10 min presentation
10 min questionnaire/demo
For presentation, students should be in formal dress
Project Presentation and Report Submission:
Will be determined later
Download