0% found this document useful (0 votes)
534 views

Advanced C++ Course File

The document contains details about a course on Advanced C++ Programming including the course objectives, timetable, student classification, and syllabus content. The course aims to teach object-oriented programming concepts in C++ and develop problem solving skills. It will cover topics such as I/O, data types, functions, arrays, pointers, strings, classes and objects. Students are classified as slow, moderate, or advanced learners and the timetable allocates hours for lectures, tutorials, debates and ICT teaching methods.

Uploaded by

Vel Murugan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
534 views

Advanced C++ Course File

The document contains details about a course on Advanced C++ Programming including the course objectives, timetable, student classification, and syllabus content. The course aims to teach object-oriented programming concepts in C++ and develop problem solving skills. It will cover topics such as I/O, data types, functions, arrays, pointers, strings, classes and objects. Students are classified as slow, moderate, or advanced learners and the timetable allocates hours for lectures, tutorials, debates and ICT teaching methods.

Uploaded by

Vel Murugan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 149

COURSE FILE

CONTENTS

Name of the Faculty: Mr.R.Kanakaraj Department: Commerce with CA


Title of the course: Advanced C++ Programming Course code:
Class: I M.Com CA Year and Semester: 2018 -18 (Even)

S. Page
Particulars
No. No.
1. Prescribed Syllabus/ Course Content
2. Objective of the Course (Not more than one page)
3. Time Table
Time allotment with Classification of
4. (i) Lectures (ii ) Group Discussion (iii) Debate (iv) ICT Enabled Teaching
(v) Tutorial (vi) Demonstration(vii) Filed Visit
Name List of the Students with Classification of
5.
(i) Slow Learners (ii) Moderate Learners (iii) Advanced Learners
6. Lecture Plan
7. Concepts to be delivered in each unit
8. At the end of the each unit the student will learn
Lecture Notes (For all the Units with Reference Books, Website Addresses and
9.
Journals)
10. Models and Problems to be worked out in the Class
11. Models and Problems to be worked out in the Tutorials
12. Possible Questions for testing the knowledge and understanding
13. List of Applications /Case Studies and the concepts to be used
Assignment I
14.
(Title and the concept involved)
15. List of skills in which the students are to be trained through the course
Relevant concepts and topics the students to be introduced (Relevant to the
16.
skills)
17. Tutorial Questions / Problems for the tutorial session
Possible questions of different types to test {i} information ii) Knowledge
18.
iii) Skills and iv) Application seperately

S. Page
Particulars
No. No.
19. Question Paper of CIA I
20. Sample Answer Scripts (Best one, Average one, Poor one)
21. Mark Sheet of CIA I
22. Retest Question paper if any
23. Mark Statement of Retest with sample scripts if any
24. Assignment II (Title and Concept involved )
25. Discussion on previous year ESE question papers (Minimum of 4 years)
26. Question Paper of CIA II (Model )
27. Sample Answer Scripts (Best one, Average one, Poor one)
28. Mark Sheet of CIA II (Model)
29. Retest Question Paper if any
30. Mark Statement of Retest with Sample Scripts if any
Internal Assessment mark under each component and final marks awarded
31.
under internal assessment
32. Marks scored in the terminal examinations
33. Final marks in the (IA + Terminal exam) in the semester
34. Attendance percentage of the students for this course
Log Book with final comments of the teacher regarding course content,
35.
duration etc.,
36. Scope of the course relevant to specific skill/job etc.,

37. Knowledge imparted to the student at the end of the course

38. Skills developed by the student at the end of the course

Signature of the Faculty Signature of HOD

Signature of Principal Signature of the Director IQAC

Name of the Faculty : R.KANAKARAJ


Department : COMMERCE (CA)
Title of the course : ADVANCED C++ PROGRAMMING
Course code : 18PCC106
Class : I M.Com (CA)
Year and Semester : 2018 – 2018 (II)
1. PRESCRIBED SYLLABUS/ COURSE CONTENT
SEMESTER: II
Contact Hrs. / Week: 05 Core Theory - 6 Credits: 04
ADVANCED C++ PROGRAMMING
OBJECTIVE: To inculcate knowledge on Object-oriented programming concepts using C+
+. PRE-REQUISITE: 9 The Student should know the C++ Concepts and basics of
computer.
UNIT I: [12 hours] Introduction to C++ - key concepts of Object-Oriented Programming –
Advantages – Object Oriented Languages – I/O in C++: Streams in C++ – Predefined
Stream Unformatted Console I/O operations – Formatted Console I/O operations – Bit fields
- C++ Declarations: Parts of C++ - Types of Token: Keywords – Identifier – Data types in C+
+ - Type Casting – Constants – Operators – Reference and Dereference Operators - Scope
Access Operator – Comma operator.
UNIT II: [12 hours] Control Structures: Decision Making and Statements: If, If ... Else,
jump, go to, break, continue, Switch case statements - Loops in C++: For, While, Do -
Functions in C++: Main () Function – Parts of Function – Pass by Arguments - Inline
functions – Function Overloading: Principles of Function Overloading. Classes and Objects:
Declaring Objects – Defining Member Functions – Static Member variables and functions –
array of objects – Friend functions – Constructor: Characteristics – Constructor with
arguments – Overloading Constructor – Constructor with Default arguments – Copy
constructor – Destructor.
UNIT III: [11 hours] Operator Overloading: Keywords Operator – Overloading unary,
binary operators – Overloading Friend functions – Inheritance: Types of Inheritance –
Single, Multilevel, Multiple, Hierarchal, Hybrid, Multi path inheritance – Virtual base
Classes – Abstract Classes.
UNIT IV:[10 hours] Pointers: Declaration – Void Pointer –Wild Pointer – Pointer to Class,
Object – this pointer – Pointers to derived classes and Base classes – Arrays: Characteristics
– array of classes – Memory models: New and delete operators – dynamic object – Binding,
Polymorphism and Virtual Functions – Pure Virtual Function.
UNIT V:[10 hours] Files: File stream classes – Steps in File Operation – File Opening modes
– Error handling functions – Exception Handling: Principles of Exception Handling –
Keywords try, throw, catch – Exception handling Mechanism – String: Declaring and
Initializing string objects – String Attributes – Miscellaneous functions.
TEXT BOOK: 1) Ashok N Kamthane, “OBJECT-ORIENTED PROGRAMMING WITH
ANSI AND TURBO C++”- Pearson Education publication. 2006.

BOOKS FOR REFERENCE: 1) E. Balagurusamy, “OBJECT-ORIENTED


PROGRAMMING WITH C++”- Tata McGraw Hill Publication, 1998. 2) Maria Litvin&
Gray Litvin , “C++ for you”- Vikas publication, 2002.

2. OBJECTIVE:
The main objective of this course is to introduce students to the basic concepts of a
selected language (such as C++) and the ability to write simple correct programs.
Topics to be covered include: I/O, data types, function definition, visiand storage
classes, parameter passing, loops, arrays, pointers, strings, files, introducing classes and
objects, constructors and destructors, function prototypes, private and public access, and
class implementation

The course presents basics of C++ programming including: Basics of C++ environment,
Data representation, Control structures, Functions, Arrays, Pointers, Strings, and Classes
that aims to:
 Arm the students with the basic programming concepts.
 Introduce different techniques pertaining problem solving skills
 Arm the students with the necessary constructs of C++ programming.

3. TIME TABLE

DO/HOUR 1 2 3 4 5 6
I _ _ _ _ _ _
II _ _ _ _ _ _
III _ _ I-PG _ _
IV _ _ I-PG I-PG _ _
V _ I-PG _ I-PG _ _

4. TIME ALLOTMENT WITH CLASSIFICATION

ICT TOTAL
CV L TUT DEB/GD DEMO
PPT VIDEO HOURS

20 20 07 05 06 05 -- 63

5. SLOW LEARNERS

SL. REGISTER
NAME OF THE STUDENTS
NO NUMBER

01 17MCC0003 ARAVINDH KUMAR. S

02 17MCC0006 HARI SHANKARI. P

03 17MCC0010 JENIFER. A

04 17MCC0011 KAVIYA. R

MODERATE LEARNERS
SL. REGISTER
NAME OF THE STUDENTS
NO NUMBER

01 17MCC0001 AJITH. R

02 17MCC0002 AKSHARA. S

03 17MCC0005 DEEPA. R

04 17MCC0008 JANANI. R

05 17MCC0012 KOWSALYA DEVI. K


06 17MCC0013 KOWSHIKA. G

07 17MCC0015 MADHUMITHA. P

08 17MCC0016 NEYA. M. P

09 17MCC0017 NIRMAL. G

10 17MCC0018 PAVITHRA. R

11 17MCC0019 PRAKASH. M

12 17MCC0020 PRAVEENA. N

13 17MCC0021 PREM KUMAR. P

14 17MCC0025 SANTHANA DEVI. M

15 17MCC0026 SAVITHA. A

16 17MCC0027 SRI RAM SABARI. P. R

17 17MCC0028 VIDHYA. R

ADVANCE LEARNERS
SL. REGISTER
NAME OF THE STUDENTS
NO NUMBER

01 17MCC0004 ASHWINI. S

02 17MCC0007 ISWARYA. S

03 17MCC0009 JANANI. C

04 17MCC0014 KOWSIKASHRI. P

05 17MCC0022 PUNITHAVALLI. R

06 17MCC0023 RAJALAKSHMI. T

07 17MCC0024 REVATHI. S
6. LECTURE PLAN: EVEN SEMESTER
NAME OF THE STAFF : R.KANAKARAJ
NAME OF COURSE :ADVANCED C++ PROGRAMMING
COURES CODE :
CLASS :I-M.COM (CA)
BATCH : 2017-2019
HO HO
DAY URS U DATE OF
SL.
ORDE DATE TOPIC PER METHODOLOGY PER COMPLETI
NO
R TOP UNI ON
IC T
UNIT – I
1 II 05.12.17 Introduction to C++ 1 LECTURE
key concepts of Object-
2 III 06.12.17 1 LECTURE
Oriented Programming
3 IV 07.12.17 Object Oriented Languages 2 CONVENTIONAL
4 II 12.12.17 I/O in C++: Streams in C++ 1 CONVENTIONAL
Formatted and Unformatted
5 III 13.12.17 1 CONVENTIONAL
Console I/O operations
C++ Declarations: Parts of C+
6 IV 14.12.17 2 LECTURE
+
17 02.01.17
7 II 19.12.17 Types of Token: Keywords 1 CONVENTIONAL
8 III 20.12.17 Identifier – Data types in C++ 1 PPT
9 IV 21.12.17 Type Casting – 2 LECTURE
10 II 26.12.17 Operators 1 LECTURE
Reference and Dereference
11 III 27.12.17 1 LECTURE
Operators
Scope Access Operator AND
12 IV 28.12.17 2 LECTURE
Comma operator.
13 II 02.1.18 Bit fields and Constants 1 NPTEL
UNIT – II
1 III 03.01.18 Control Structures 1 LECTURE
Decision Making and
2 IV 4.1.18 2 LECTURE
Statements
3 II 09.1.18 Functions in C++ 1 CONVENTIONAL
4 III 10.1.18 Inline functions 1 CONVENTIONAL
5 IV 11.1.18 Function Overloading 2 CONVENTIONAL
Principles of Function
6 IV 18.1.18 2 LECTURE
Overloading
7 II 23.1.18 Classes and Objects 1 CONVENTIONAL
8 III 24.1.18 Declaring Objects 1 PPT
Defining Member Functions 16 07.02.18
9 IV 25.1.18 and Static Member variables 2 LECTURE
and functions
10 II 30.1.18 array of objects 1 LECTURE
11 III 31.1.18 Friend functions 1 LECTURE
IV Constructor: Characteristics –
12 01.02.18 2 NPTEL
Constructor with arguments
Overloading Constructor –
13 II 06.02.18 Constructor with Default 1 CONVENTIONAL
arguments
14 III 07.02.18 Copy constructor – Destructor 1 TUTOR
HO HO
DAY URS U DATE OF
SL.
ORDE DATE TOPIC PER METHODOLOGY PER COMPLETI
NO
R TOP UNI ON
IC T
UNIT – III
1 I 11.2.18 Operator Overloading 1 LECTURE
2 II 12.2.18 Keywords Operator 1 LECTURE
Overloading unary operators
3 IV 15.2.18 2 CONVENTIONAL
and binary operators
Overloading Friend functions
4 II 20.2.18 1 CONVENTIONAL
and Types of Inheritance
10 28.2.18
Single, Multilevel, Multiple
5 III 21.2.18 1 CONVENTIONAL
Inheritance
IV Hierarchal and Multi path
6 21.2.18 2 CONVENTIONAL
inheritance
7 II 27.2.18 Virtual base Classes 1 PPT
8 III 28.2.18 Abstract Classes 1 LECTURE
UNIT – IV
1 I 1.3.18 Pointers: Declaration 1 LECTURE
2 II 6.3.18 Void Pointer –Wild Pointer 1 LECTURE
3 III 7.3.18 Pointer to Class, Object 1 CONVENTIONAL
this pointer – Pointers to
4 IV 8.3.18 derived classes and Base 2 CONVENTIONAL
classes
Arrays, array of classes, 09 15.3.18
5 II 13.3.18 1 CONVENTIONAL
Memory models
III New and delete operators,
6 14.3.18 dynamic object, Binding 1 CONVENTIONAL
Virtual Functions, Pure
7 IV 15.3.18 2 PPT
Virtual Function
UNIT – V
Files, File stream classes,
1 II 20.03.18 Steps in File Operation, File 1 LECTURE
Opening modes
Error handling functions,
2 III 21.3.18 Principles of Exception 1 LECTURE
Handling
08
Keywords try, throw, catch, 29.3.18
3 IV 22.03.18 Exception handling 2
Mechanism, String
Declaring and Initializing
4 II 27.03.18 1 PPT
string objects
5 III 28.03.18 Miscellaneous functions 1 CONVENTIONAL
6 IV 29.03.18 Example program 2 CONVENTIONAL

7. CONCEPTS TO BE DELIVERED IN EACH UNIT


UNIT CONCEPTS
I Introduction to C++ - key concepts, Data type, Operators

II Control Structures, Function Overloading, Classes and Objects,


Constructor

III Operator Overloading,Inheritance,Virtual base Classes

IV Pointers, Arrays
V File concepts, Exception Handling

8. AT THE END OF THE EACH UNIT THE STUDENT WILL LEARN

Unit – I:

 Oops concepts
 Various types of function
 Data type

Unit – II:

 Defining and declaring member functions


 Friend functions
 Constructors and destructors

Unit – III:

 Inheritance and its concepts


 Operator overloading

Unit – IV:

 Pointers
 Arrays
 Virtual functions

Unit – V:

 Files
 Strings
 Exception handling

9. LECTURE NOTES

LECTURE NOTES

UNIT I
Introduction to C++ - Key concepts of OOP – Advantages – OO Languages – I/O in C++ - C+
+ declarations. Control structures: Decision making statements – if… else, jump, go to, break,
continue, Switch case statements. Loops in C++: for, while, do… while loops-Functions in C++ -
Inline functions – Function overloading

Evolution of C++
C++ is an object – oriented programming language and is considered to be an extension
of C. Bjarne Stroustrup at AT&T Bell Laboratories, Murray Hill, New Jersey (USA) developed it
in the early eighties of twentieth century. Stroustrup, a master of Simula67 and C, wanted to
combine the features of both the languages into a more powerful language that could support
object – oriented programming with features of C. Various ideas were derived from SIMULA 67
and ALGOL68. Stroustrup called the new language “C with classes”. However, in 1983, the
name was changed to C++. C++ is an extended version of C.

PRINCIPLES OF OBJECT-ORIENTED PROGRAMMING

Software Evolution

Many programming approaches have been into play from the time of inventions
of the computer. These techniques include modular programming, top-down programming,
bottom-up programming and structured programming. The primary motivation in each case has
been the concern to handle the increasing complexity of programs that are reliable and
maintainable.

To build today’s complex software, it is just enough to put together a sequence of


programming statements and set of procedures and modules but to incorporate sound
construction techniques and program structures that are easy to comprehend, implement and
modify. C, structured programming was a powerful tool that enabled programmers to write
moderately complex programs fairly easily. However, as the programs grew, even the structured
approach failed to show the desired results in terms of bug-free, easy-to-maintain and reusable
programs.

OOP is an approach to program organization and development that attempts to


eliminate some of the pitfalls of conventional programming methods by incorporating the best of
structured features with several powerful new concepts.

PROCEDURE AND OBJECT -ORIENTED PARADIGM

Characteristics of Procedure-Oriented Programming.


 Emphasis is on during things (algorithms).
 Large programs are divided into smaller programs known as functions.
 Most of the functions share global data.
 Data move openly around the system from function to function.
 Functions transform data from one form to another.
 Employs top-down approach.
Object-Oriented approach overcomes some of the flaws encountered in the procedural approach.
OOP treats data as a critical element in the program development and it has the following
characteristics as

 Emphasis is on data rather than procedure.


 Programs are divided into what are known as objects/
 Data structures are designed such that they characterize objects.
 Functions that operate on the data of an object are tied together in the data
structures.

 Data is hidden and cannot be accessed by external functions.


 Objects may communicate with each other through functions.
 New data and functions can be easily added whenever necessary.
 Follows bottom-up approach.

Object Oriented Programming:

Object oriented programming is a kind of innovation in programming languages


and its important because it depicts the real world situation in a much simpler form. It is
more reliable, less confusion and less complexities. C++ is one such object oriented
programming language.

Object Oriented programming has a lot of new concepts like.

 Any real world situation can be clubbed as objects


 Class is a collection of objects which is of similar type
 Object is just combining the data and the functions that operate on that data. It is
an instance of a particular class.
Encapsulation - The Wrapping up of data and functions into a single unit (called
class) is known as encapsulation.

Data Hiding - The data is not accessible to the outside world and only those functions, which
are wrapped in the class, can access it. This insulation of data from direct access by the
program is called data hiding.
Polymorphism – The ability to take more than form is known as polymorphism.
Inheritance - Inheritance is the process by which objects of one class acquire the
properties of objects of another class. It provides the concept of reusability.

BASIC CONCEPTS OF OOPS

Object oriented programming has the following concepts:

 Objects
 Classes
 Data abstraction
 Data encapsulation
 Inheritance
 Polymorphism
 Dynamic Binding
 Message Passing
1. Objects:
Objects are basic run-time entities in an object-oriented system. They may
represent a place, a person, a bank account or any item that the program must handle.
Programming problem is analyzed in terms of objects and the nature of
communication between them.

When a program is executed, the objects interact by sending messages to one


another. For example, if “customer” and “account” are two objects in a program, then
the customer object may send a message to the account object requesting the bank
balance.

2. Classes:
A class is a collection of objects of similar type. For example, mango, apple and
orange are members of the class fruit. The entire set of data and code of an object
can made a user-defined data type with the help of a class. Once a class is defined, we
can create any number of objects belonging to that class.

3. Data abstraction:
Abstraction refers to the act of representing essential features without including
the background details or explanations. Classes use the concept of abstraction and are
defined as a list of abstract attributes such as size, weight and cost, and functions to
operate these attributes.

4. Data encapsulation:
The wrapping up of data and functions into a single unit (called class) is known as
encapsulation. Data encapsulation is the most striking feature of a class. The data is
not accessible to the outside world and only those functions which are wrapped in the
class can access it.

5. Inheritance:
Inheritance is the process by which one class acquires the properties of objects of
another class. It supports the concept of hierarchical classification. 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.

6. Polymorphism:
Polymorphism means the ability to take more than one form. For example, an
operation may exhibit different behavior in different instances. The behavior depends
upon the types of data used in the operation. For example, consider the operation of
addition. For two numbers, the operation will generate a sum. If the operands are of
strings the result will be the concatenated string.

7. Dynamic Binding:
Binding refers to the linking of a procedure call to the code to be executed in
response to the call. Dynamic binding means that the code associated with a given
procedure call is not known until the time of the call at run-time.

8. Message Passing:
An object-oriented program consists of sets of objects that communicate with
each other. Objects communicate with one another by sending and receiving
information in the same way as people pass messages to one another. Message
passing involves specifying the name of the object, the name of the function
(message) and the information to be sent.

Example: employee salary (name);

BENEFITS OF OOPS:

This new technology promises greater productivity, better quality software and lesser
maintenance cost. Other advantages are

 Existing classes can be extended using inheritance that avoids redundant code.
 Data hiding helps the programmer to build secure programs and so it cannot be
invaded by code in other parts of the program.
 Multiple instances of an object can co-exist with out any interference.
 It is easy to partition work in a project based on objects
 Object oriented systems can be easily upgraded from small to large systems
 Communication between objects is simpler.
 Software complexities are easily manageable.
 Few features to be incorporated in Object oriented systems are:

OBJECT-ORIENTED LANGUAGES:
Object oriented programming languages are classified into two types based on the
concepts they support. The two types are

 Object-based languages
 Object-oriented languages

Object-based languages are that style of programming that supports encapsulation


and object identity. The other features available in this type are Data hiding, Automatic
initialization and clear up of objects, operator overloading. It also supports programming
with objects. The two features that are not supported by object-based languages are
dynamic binding and inheritance. E.g. Ada
Object-oriented languages incorporates in it features like data hiding, encapsulation,
operator overloading, automatic initialization and clear-up of objects, along with
inheritance and dynamic binding. E.g. C++, Object Pascal, Small Talk.In general,

Object-oriented language=Object-based + inheritance + Dynamic binding

APPLICATIONS OF OBJECT-ORIENTED PROGRAMMING:

The most popular applications of object-oriented programming have been in the area of
user interface design such as windows. Promising areas for application of oops includes:
 Real-time systems
 Simulating and modeling
 Object-oriented databases
 Hypertext, Hypermedia and expert text
 Artificial Intelligence and expert systems
 Neural networks and parallel programming
 Decision support and office automation systems
 Computer Integrated Manufacture/Computer Aided Design and Manufacture etc

Object-oriented paradigm came from a language, matured into design and has now
moved into analysis. This technology is going to change the way software engineers
think, analyze, design and implement systems in future.

INPUT AND OUTPUT IN C++

Streams in C++

Stream is a flow of data in bytes in sequence. If data is received from input devices in
sequence then it is called as source stream and when the data is passed to output devices then it is
called destination stream. Data in source stream can be used as input data by the program. So,
the source stream is also called as input stream. The stream is an intermediator between I/O
devices and the user.

Predefined streams

Pre-defined streams are also called as standard I/O objects. These streams are
automatically activated when program execution starts. Some of the pre-defined streams are

 Cin – Standard input, usually keyboards, corresponding to stdin in C.


 Cout – Standard output, usually screen, corresponding to stdout in C.
 Clog – A fully buffered version of cerr. It controls error messages that are passed
from buffer to the standard error device.
 Cerr – Standard error output, usually screen, corresponding to stderr in C.

Stream classes

All C++ stream classes are declared in the header file iostream.h. The file iostream.h
must be included in the program if we are using functions of these classes. The class istream and
ostream are derived classes of base class ios. The iostream contains formatting of both istream
and ostream classes.

The C++ I/O system contains a hierarchy of classes that are used to define various
streams to deal with both the console and disk files. These classes are called stream classes. The
following figure shows the hierarchy of the stream classes used for input and ouptput operations
with the console unit. These classess are declared in the header file iostream.h. This file should
be included in all the programs that communicate with the console unit.

ios is the base class for istream and ostream which are, in turn, base classes for iostream.
The class ios is declared as virtual base class so that only one copy of its members are inherited
by the iostream. The class ios provides the basic support for formatted and unformatted input
while the class ostream provides the facilities for formatted output. The class iostream provides
the facilities for handling both input and ouput streams.

Class : ios

 Contains the basic facilities that are used by all the input and output
classes
 Declares constants and functions that are necessary for handling formatted
input and output operations

Class: istream
 Inherits the properties of ios.
 Declares input functions such as get(), getline() and read()
 Contains overloaded extreaction operator >>.

Class : ostream

Inherits the properties of ios.

 Declares for the output functions such as put() and write().


 Contains the overloaded insertion operator <<.

Class : iostream

 Inherits the properties of ios, istream, ostream through multiple


inheritance and thus contains all the input and output functions.

Ios

ostream
istream Streambuf

iostream

Ostream_withstream
Istream_withassignn Iostream_withassign

Formatted and Unformatted data

Formatting means representation of data with different settings as per the requirement of
the user. The data accepted or printed with default setting by the I/O function of the language is
known as unformatted data. The data obtained with manipulators are known as formatted data.

Unformatted Console I/O operations

Overloaded operators >> and <<

Objects cin and cout for the input and output of data of various types. This has been
made possible by overloading the operators .. and << to recognize all the basic data types.
The input operator >> is overloaded in the istream class and the >> is overloaded in the
ostream class.

Statement for reading data from the keyboard.

cin>>variable1>>variable2>>…..

The input can be entered separated by white spaces or by line space like Data1 data2 data3…
The >> operator gets character by character and assigns to the indicated location. The reading for
a variable is terminated when the operator encounters an white space or a character that does not
match the destination type.
For e.g.
int code;

cin>>code;

then the data such as

45

or

45D causes a termination.

The general format for displaying a data is

cout<<item1<<item2<<item3<<….

put() and get() functions

The istream and ostream classes define two member functions get() and put()
respectively to handle single character input/output operations.

Two types of get() functions.

1. get(char *) – Assigns the input character to its argument.

char c;

cin.get(c); //gets a character from the keyboard

2. get((void) – Returns the input character.


char c;
c=cin.get(); //cin.get(c) is replaced
In this case, the value returned by the function get() is assigned to the variable c.
The function put(), a member ostream class is used to output a line of text, character by
character.
For e.g.,
cout<<put(‘x’); // displays the character x
cout.put(ch); // displays the value of the variable ch.

Number can be as an argument to the function put(). For e.g.,


cout.put(68);

getline() and write() functions

A line of text can be read and displayed using line-oriented input/output functions
getline() and write() functions. The getline() function reads a whole line of text that
ends with a newline chracter which is transmitted by the RETURN key. It is invoked
by using the object cin as follows
cin.getline(line, size);

This function reads character input into the variable line. The reading is
terminated when it encounters a newline character such as ‘\n’ or when the size-1
characters are read.
For e.g.,
char name[20];
cin.getline(name,20);

‘How are u’ is typed as input and if return is pressed then the input is assigned to
the array variable name. If the length of the text exceeds 20 characters then the
reading is terminated. Here the blank spaces are also included in the text length.

In case of cin, it can read strings that do not contain white spaces.

The write() function displays an entire line and has the following form:

cout.write(line,size);

The first argument line represents the name of the string to be displayed
and the second argument size indicates the number of characters to be displayed.

For eg.

cout.write(string1,3);

Displays the 3 characters of the string1.

Formatted console I/O operations

C++ supports a number of features for formatting the output such as:

 ios class functions and flags


 Manipulators
 user-defined output functions
ios class functions

The ios class contains a large number of member functions that help to format the output. They
are

i) Width() – It specifies the required field size for displaying an output value. An object
is used to the invoke this member function. For eg. Cout.width(w) where w is the
field width.The output will be printed in a field of w characters wide at the right end
of the field.
cout.width(5);

cout<<543<<”\n”;

5 4 3

The field width should be specified for each item. C++ never truncates the values
and therefore if specified field width is smaller than the size of the value to be
printed, C++ expands the field to fit the value.

ii) Precision()
It specifies the number of digits to be displayed after the decimal point of a
float value. By default the floating numbers are printed with six digits after the
decimal point. The function precision() helps to specify the number of digits
to be displayed after the decimal point explicitlyThe function is invoked as:

cout.precision (d);

For eg,
cout.precision(3);
cout<<sqrt(2);
cout<<3.1454;
cout<<2.5049;
The output for the above settings would be of the form:1.141 ( truncated)
3.142 (is rounded to the nearest cent)(no trailing zeros).

Precision() retains the setting in effect until it is reset.

iii ) Fill() – It specifies a character that is filled in the unused portion of a field.

Printing values using much larger field widths than required by the values. The unused portion
of the field are filled with white spaces by default. Fill() function can be used to fill the unused
positions by any desired character. It is used in the following form

cout.fill(ch); where CHANCHAL represents the character which is used for filling
the unused positions.

cout.fill(“*”);

cout.width(10);

cout.5250<<”\n”;

The output would be as:

* * * * * * 5 2 5 0

iv)Flags, Bit-fields and setf() Formatting


Setf() – It specifies the format that can control the form of output display such as
left and right justifications

Unsetf() – It clears the flags specified

The function width() prints the number ortext right-justified in the field width
created. But it is a practise print text left-jusitified. To do so, setf () is used.

The setf() a member function of the ios class can be used as follows:

cout.setf(arg1,arg2); where arg1 is one of the formatting flags defined the class ios.
The formatting flag specifies the format action required for the output. Another ios
constant, arg2, known as the bit field specifies the group to which the formatting flag
belongs.

cout.fill(‘*’);

cout.setf(ios::left,ios::adjustfield);

cout.width(15);

cout<<”TABLE 1”<<”\n”;

Produces the following output

T A B L E 1 * * * * * * * *

Displaying Trailing zeros and plus sign


Be default, trailing zeros and plus sign are not displayed. To these, setf()
can be used.

cout.setf(ios::showpoint); will cause cout to display trainling zeros and


trailing decimal point.

Cout.setf(ios::showpos); will cause cout to display before a positive


number.

For eg.

cout.setf(ios::showpoint);

cout.setf(ios::showpos);

cout.precision(3);

cout.setf(ios::fixed,ios::floatfield);
cout.setf(ios::internal,ios::adjustfield);

cout.width(10);

cout<<275.5<<”\n”;

+ 2 7 5 . 5 0 0

The flags showpoint and showpos do not have any bit fields and they are used as a single
argument in setf(). This is possible because setf() is an overloaded function in the class ios.
The list of flags in the table below do not possess a named bit field. These flags can be set or
cleared independently.

Flags Meanings

ios::showbase use base indicator on output

ios::showpos print + before positive numbers

ios::showpoint show trailing zeros and decimal


point

ios::uppercase use uppercase letters for hex output

ios::skipus skip white space on input

Flags Meanings

ios::unitbuf flush all streams after insertion

ios::stdio flush stdout and stderr after insertion

Managing output with manipulators


The header file iomanip.h provides a set of functions called manipulators which can be used

to manipulate the output formarts. They provide the same functions as ios member functions

and flags. Two or more manipulators can be used as a chain in one statement as follows:

cout <<manip1<<manip2<< manip3<<item;

cout <<manip1<<item1<<manip2<< tem2;


This is made useful when several columns of output is to be displayed.

Manipulator Meaning Equivalent

setw(int w) set the field width to w width()

setprecision(int d) set the floating point precision to d


precision()
setfill(int c) set the fill character to c fill()

setiosflags(long f) set the format flag f setf()

resetiosflags(long f) clear the flag specified by f


unsetf()

endl insert new line and flush stream “\n”

For e.g. cout<<setw(10)<<12345;

The above statement prints the value 12345 right justified in a field width of 10 characters. The
left justification can be achieved using the syntax:
cout<<setw(10)<<setiosflags(ios::left)<<12345;
The format of output for two or more values can be used in a single statement as follows:
cout<<setw(5)<<setprecision(5)<<1.2345<<setw(10)<<setprecision(4)<<sqrt(2)
<<setw(15)<<setprecision(ios::scientific)<<sqrt(3);
The above will print all the three values in one line with the field sizes of 5,10, and 15
respectively.
Each output is controlled by different set of format specifications. The manipulators and ios
functions can be jointly used in a program. There is a major difference between ios functions and
manipulators. The ios member functions returns the previous state which can be used later, it
necessary. But the manipulator does return the previous format state. In this case, the old format
states.
cout.precision(2); //previous state
int p=cout.precision(4) //current state
When the above statements are executed then p will hold the value of 2 as
the previous state and the new format state will be 4. We can restore the previous
format state using the statement,
cout.precision(p); //p=2
C++ Statements

C++ is a collection of functions. Execution begins at main(). Every C++ program must have a

main(). C++ is a free-form language. Like C, C++ terminates with semicolon.


C++ introduces a new comment symbol //(double slash). Comments start with a double
slash symbol and terminate at the end of the line. A comment may start anywhere in the line and
whatever follows till the end of the line is ignored. There is no closing symbol.

For e.g.

//This is an example of

//C++ program to illustrate

//some of its features.

The C comment symbols /*, */ are still valid and more suitable for multilane comments.
For e.g.

/*This is an example of

C++ program to illustrate

some of its features.*/

Output Operator
C++ introduces two new C++ features, cout and <<. The identifier cout is a predefined
object that represents the standard output stream in C++. The standard output stream represents
the screen.

The operator << is called the insertion or put to operator. It inserts(or sends) the contents
of the variable on its right to the object on its left.

For e.g. cout << “C++ is better C.””;

cout << string;

Input Operator

The identifier cin is a predefined object that represents the standard input stream
in C++. The standard input stream represents the keyboard.

The operator >> is called the extraction or get from operator. It extracts(or takes) the
value from the keyboard and assigns it to variable on the its right.

For e.g. cin >> string;

Structure Of C++ Program

A typical C++ program would contain four sections as shown in the diagram. These
sections may be placed in separate code files and then compiled independently or jointly.

Structure of a C++ Program


It is a common practice to organize a program into three separate files. The class declarations
are placed in a header file and the definitions of member functions go into another file. This
approach enables the programmer to separate the abstract specification of the interface (class
definition) from the implementation details (member functions definition). Finally, the main-
program that uses the class is placed in a third file which "includes" the previous two files as
well as any other files required.
This approach is based on the concept of client-server model. The class definitions
including the member functions constitute the server that provides services to the main program
known as client. The client uses the server through the public interface of the class.

Tokens, Expressions and Control Structures

Tokens
The smallest individual units in a program are known as tokens. C++ has the following
tokens:


Keywords

Identifiers

Constants

Strings

Operators.
A C++ program is written using these tokens, white spaces, and the syntax of the
language.

Keywords
They are explicitly reserved identifiers and cannot be used as program variables or other
user-defined program elements.

C++ Keywords

 char
 int
 if
 then etc
Identifiers
Identifiers refer to the names of variables, functions, arrays, classes etc. created by the
programmer. Each language has its own rules for naming these identifiers. They are both
common to both C and C++:

 Only alphabetic characters,digits and underscores are permitted.


 The name cannot start with a digit.
 Uppercase and lowercase letters are distinct.
 A declared keywoird cannot be used as a variable name.
A major difference between C and C++ is the limit on the length of a name. While ANSI
C recognizes only the first 32 characters in a name, C++ has no limit the length of a
name.

Basic Data Types


Both C and C++ compilers support all the built in data types. With the exception of void,
the basic data types may have several modifiers preceding then to the serve the needs of
various situations. The modifiers signed, unsigned , long, and short may be applied to
character and integer basic data types.

Two normal uses of void are

1) to specify the return type of a function when it is not returning any value
2) to indicate an empty argument list to a function.
E.g. void fn1(void)

Size and range of C++ basic data types

Hierarchy of C++ data types


User-Defined Data Types

Structures and Classes

Data types such as struct and union in C are also valid in C++. C++ also permits us to
define another user-defined data type known as class. The class variables are known as objects,
which are the central focus of object –oriented programming.

Enumerated Data type

An enumerated data type is another user-defined type which provides a way for attaching
names to number , thereby increasing comprehensibility of the code. The enum keyword
automatically enumerates a list of words by assigning then values(0,1,2,..).

For e.g.

enum color(red,blue,green);

color background; // background is of type color

Control Structures
One method of achieving the objective of an accurate, error –resistant and maintainable

code is to use one or any combinations of the following three control structures:

1. Sequence structure (Straight line)


2. Selection structure ( branching)
3. Loop structure (Iteration or repetition).
These structures are implemented using one-entry, one-exit concept .

The if statement

The if statement is implemented in two forms:

1) Simple statement
if (conditional exp)

action1;

action2;

action3;

2) if..else statement.
if (conditional expression)

action1;

else

action2;

action3;

The switch Statement

This is a multiple-branching statement where, based on a condition, the control is transferred to


one of the many possible points. This is implemented as follows:
switch (expression)
{

casel:
{
action 1;

case2:
{
action2:

case3:

actions:
}
default:
{
action4;
}
}
action 5;

The do-while Statement

The do-while is an exit-controlled loop. Based on a condition, the control is transferred back to
a particular point in the program. The syntax is as follows:
do
{
action 1;
}
while(condition is true);
action2;

The while Statement


This is also a loop structure, but is an entry-controlled one. The syntax is as follows:
While (condition is true)
{
action 1;
}
action 2;

The for Statement


The for is an entry-entrolled loop and is used when an action is to be repeated for a
predetermined number of times. The syntax is as follows:
for (intial value;test;increment)
{
action1;
}
action2;

Operator Precedence
C++ enables multiple meanings to the meanings to the operators, their association and

precedence remains the same. For example, the multiplication operator will continue having

higher precedence than the add operator. The precedence and associativity of all the C++

operators are listed below in the order of decreasing precedence.

Operator Associativity

:: left to right

- . ( ) [] postfix++ postfix-- left to right

prefix++ prefix-- ~ ! unary + unary –

unary * unary & (type) sizeof new delete right to left

- * * left to right
* / % left to right

+- left to right

<< >> left to right

< <= > >= left to right

== != left to right

& left to right

^ left to right

| left to right

&& left to right

|| left to right

?: left to right

= *= /= %= += -=

<<= >>= &= ^= |= right to left

FUNCTIONS IN C++

Introduction
Functions play an important role in programming. Dividing a program into function is
one of the major principles of top-down, structured programming. Another advantage is
reducing the size of the programs. As a result, functions remain as the building blocks of C+
+ programs with some additional features.

The Main function


In ANSI C,

The definition of main( )

Main( )

//main program statements


}

The starting point for the execution of a program is main ( ) that does not return any value. In
C++, main() returns a value of type int to the operating system. Therefore, C++ explicity
defines main( ) as
int main( )
{

……
……

return(0);

The functions that have a return value should use the return statement for termination.

Parts Of Function

A function has the following parts:

 Function Prototype declaration


 Definition of a function
 Function call
 Actual and formal arguments
 The return statement.

Function Prototype
The prototype describes the function interface to the compiler by giving details such as the
number and type of arguments and the type of return values. When a function is called, the
compiler ensures that proper arguments are passed or the return value is correct. Any
violation in matching the arguments or the return types will be indicated by the compiler at
the time of compilation itself. In C++, function prototyping is essential.Function prototyping
is a declaration statement in the calling program and with the syntax as follows:
type function-name(argument-list);

The argument list contains the types and names of arguments that must be passed to
the function. Each argument variable must be declared independently inside the parentheses.
The variable names in the argument list can be excluded.

For e.g.

float mean(int a, int b)

Function Definition
The block of statements followed by function declarator is called as function declarator.
The declarator and function prorotype declaration should match each other. The function
body is enclosed with curly braces.

Function Call

A function gets activated only when a call to function is invoked. A function must be
called by its name, follwed by argument list enclosed in parenthesis and terminated by semi-
colon.

Actual and Formal aguments

The arguments declared in caller function and given in the function call are called as
actual arguments. The arguments declared in the function declarator is known as formal
arguments.

The return Statement

The return statement is used to return value to the caller function. The return statement
returns only one value at a time. When a return statement is encountered, compiler transfers
the control of the program to caller function.

PASSING ARGUMENTS

The main objective of passing argument to function is message passing.


The message passing is also known as communication between two functions i.e., caller and
callee functions. There are three methods by which we can pass values to the function. These
methods are.

a) Call by Value
b) Call by address
c) Call by reference
a) Call by Value
In this type, value of actual argument is passed to the formal argument and
operation is done on the formal arguments. Any change in the formal argument does not
effect the actual argument because formal arguments are photocopy of actual arguments.

b) Call by Address
In this type, instead of passing values, addresses are passed. Function
operates rather than values. Here the formal arguments are pointers to the actual arguments.
Hence any changes made in the arguments are permanent.

c) Call by Reference
C++ reference types, declared with & operator are nearly identical but not exactly
same to pointer types. They declare aliases for object variables and allow the programmer to
pass arguments by reference to functions.

A program that uses pass by value, reference and address.


#include<iostream.h>

void main()

void funA(int s);

void funB(itn &);

void funC(int *);

int s=4;

funA(s);

cout<<”\n Value of s= “<<s<<”Address of s:”<< unsigned(&s);

funB(s);

cout<<”\n Value of s=”<<s<<”Address of s:”<<unsigned(&s);

funC(s);

cout<<”\n Value of s=”<<s<<”Address of s:”<<unsigned(&s);

void funA(int i)

i++;

void funB(int &k)

k++;

void funC(int *j)

++*j;

}
OUTPUT

Value of s=4 Address of s: 4096

Value of s=5 Address of s: 4096

Value of s=6 Address of s: 4096

Return by reference
A reference allows creating alias for the pre-existing variable. A reference can also be
returned by the function. A function that returns reference variable is in fact an alias for referred
variable. This technique of returning reference is used to establish cascade of member functions
calls in operator overloading.

Default arguments

Usually, a function is called with all arguments as declared in function prototype


declaration and function definition. C++ compiler lets the programmer to assign default values in
the function prototype declaration. When the function is called with less parameter or without
parameters, the default values are used for operations.

INLINE FUNCTIONS
The concepts in using functions in programs is to save memory space, which becomes
appreciable when a function is called many times. Every time a function is called, it takes a
lot of extra time in executing a series of instructions for tasks such as jumping to the
function, saving registers, pushing registers, pushing arguments into the stack and returning
to the calling function. When a function is small, a substantial percentage of execution time
is spent in such overheads.
In C++, solution to above problem is the use of inline functions. An inline function is a
function that is expanded in line when it is invoked. The compiler replaces the function call
with the corresponding function code, Definition of inline functions is
inline function-header
{

function body
}
Example:
inline double cube(double a)
{
return(a*a*a);
}
Inline function is invoked by statement like
c = cube(2.0);
All inline functions must be defined before they are used. The speed benefits of inline
functions are lost as the size of inline function grows. In such cases, the use of normal
function will be more meaningful. As a result, the function are made inline when they are
small enough to be defined in one or two lines.
The keyword inline indicates a request to the compiler and this request is ignored if
the function is too long or complicated. The other situations when inline functions do not
work are
 If the function has a loop, switch or goto statements
 If the function contains static variables
 If the function is recursive
 If the return statement does not exist
Inline function is advantageous in the fact that the program runs faster but it
consumes memory because the function is inserted at each point the function is called.

FUNCTION OVERLOADING

Defining multiple functions with same name is known as function overloading or


function polymorphism. Polymorphism means one function having many forms. The overloaded
function must be different in its argument list and with different data types.

A program to find the area of the rectangle, triangle, and sphere using function overloading.

#include<iostream.h>

#define pi 3.14285

int calcarea(int length, int breadth);

float calcarea(double base, double height);

float calcarea(double radius);

void main()

int area1;

int area2;

double area3;
area1=calcarea(10,20);

area2=calcarea(4.5,2.1);

area3=calcarea(3.12145);

cout<<”Area of rectangle is :”<<area1<<endl;

cout<<”Area of triangle is :”<<area2<<endl;

cout<<”Area of sphere is:”<<area3<<endl;

int calcarea(int length, int breadth)

return (length*breadth);

float calcarea(double base, double height)

return ((0.5)*base*height);

float calcarea(double radius)

return ((4/3)*pi*radius*radius);

EXPECTED QUESTIONS

1. Explain the key concepts of OOP.


2. Mention the advantages of OOP languages.
3. What are formatted and unformatted input/output functions?
4. List the flags without bit fields with their working.
5. What are type modifiers? Why are they essential in C++?
6. Explain typecasting. What are explicit and implicit type conversions?
7. Explain the use of comma operator.
8. Explain the need of control structures in C++.
9. What are the differences between while and do-while loop statements?
10. Describe different parts of a function.
11. What are inline functions? Discuss its advantages and disadvantages.
12. What is function overloading? Explain with an example.
UNIT II:

Classes and objects: Declaring objects - defining member function - static member variables
and functions - array of objects - Friend functions - Overloading member functions - Bit
fieldsand classes - constructors and Destructors – Characteristics - calling constructor and
destructors - Constructors and destructors with static members.

CLASSES AND OBJECTS The most important feature of C++ is the class. Class is the
mechanism to create objects. A class is an extension of the idea of structure used in C.
Limitation of C structures is that it does not permit data hiding. As a result, C++ has
expanded its capabilities such as including both variables and functions. This is called in C++
as a class. The basic difference between a structure and a class in C++ is that, by default, the
members of a class are private while,by default, the members of a structure are public.
Specifying a class A class is a way to bind data and its associated functions together. It is
declared using the class keyword. When a class is defined, a new abstract data type is created
that can be treated like any other built-in data type. A class consists of 2 parts

 class declaration –specifies the type and scope of its members

 class function definitions – tells how the class functions are implemented

The syntax of a class declaration is class class_name

{ private:

variable declarations;

function declarations;public : variable declarations;

function declarations;

};

The class body contains the declaration of variables and functions which are collectively
called as

members. The variables declared inside the class are known as data members and the
function are

known as member functions.

The body of the class is enclosed within the curly brackets and terminated by a semicolon.

There are two visibility labels

 private

 public

under which members of class are grouped as shown in the syntax.


By default, all functions and variables declared inside a class are private to that class. To

declare public members, the public keyword is used followed by colon. All functions and
variables

declared public are accessible by other members of the class and by any other part of the
program

that contains the class. The binding of data and functions together in a class is called as

encapsulation. Example:

Class item

public:

int no; // private variable declarations

float cost;

void getdata( int a, float b);

void putdata();

};

Declaring objects Object is an instance of a class. Each object of the class has its own copy
of

every variable declared within the class.Syntax : Class_name objectname;Example:

Item x;

Creates a variable x of type item.

Multiple objects can also be created.

Item x,y,z; creates x,y and z as objects of item.

Objects can be created by placing their names immediately after the class declaration

Example:

Class item

int no; // private variable declarations

float cost;
public:

void getdata( int a, float b);

void putdata();

} x, y, z;

Accessing class members

The object can access the public member variables and functions of a class by using operator

dot (.) and arrow (-&gt;)

The syntax is follows

Object-name operator member name

Example.

here a is the object and show() is a member function.

*c is a pointer to class item; Therefore arrow operator is used to access the member.

The keyword public is used to access the member variables of class directly. The public
keyword is

written inside the class and is terminated with a colon(:)

The private keyword is used to prevent direct access to member variables or function by the
object.

The class members by default are private.

The private keyword is terminated by colon.

Defining member functions Member functions can be declared in 2 places

a.show();

c-&gt;show();

 Outside the class definition

 Inside the class definition

Outside the class definition:

Member functions that are declared inside a class has to be defined outside the class. The

definitions are like normal functions. An important difference between a member function
and a
normal function is that the member function has an identity label in the header. The label tells
the

compiler which class the function belongs to. To define a member function, you must link the
name

of the function with the name of the class and the scope resolution operator.Declaration :

return type class_name:: function_name(argument declaration)

{ Body of function//}The membership label class-name:: tells the compiler that the

function function-name belongs to class class-name. The characteristics of the member

function are

 Different classes can have the same function name. The membership label identifies

the scope.1

 A member function can access the private data of the class.

 A member function can call another member function directly, without using the dot

operator.

Inside the class definition

When the function definition is inside the class definition, the function definition replaces

the function declaration. A function defined inside the class is treated as inline and is bound
by the

restrictions for an inline function.

Example:

// program to show member function definitions

# include&lt; iostream.h&gt;

class item

public:

int no; private data members

float cost;

void getdata(int a, float b); // outside function definition


void putdata() // inside function definition

cout&lt;&lt;”Item number : “&lt;&lt;no&lt;&lt;endl;

cout&lt;&lt;”Item Cost : “&lt;&lt;cost&lt;&lt;endl;

};

void item :: getdata (int a, float b)

no=a; uses membership label

cost=b;

Void main()

item x;

x.getdata(100,75.5); // call to member function

x.putdata();

Output:

Item number : 100

Item cost : 75.5

Private member functions

It is possible to declare function in private section like data variables. To execute private

member function, it must be invoke by public member function of the same class. A member

function of one class can invoke any other member function of its own class. This method of

invoking function is known as nesting of member function. The member function can be
invoked by

its name terminated by semicolon like normal function.


#include&lt;iostream.h&gt; class Arith

{ int a; int b; int add(); int subtract(); int multiply(); int divide();public : void

setdata(int x, int y); void display();};

void Arith :: setdata(int x, int y)

{ a = x; b = y;}

int Arith :: add()

{ return (a+b);}

int Arith :: sub()

{ return(a-b);}

int Arith :: multiply()

{ return(a*b);}

int Arith ::divide()

{ return(a/b);}

void Arith :: display()

{ cout&lt;&lt;”Sum of a and b:”&lt;&lt;add();//private member function called

cout&lt;&lt;”Difference between a and b:”&lt;&lt;subtract(); cout&lt;&lt;”Product of a and

b:”&lt;&lt;multiply(); cout&lt;&lt;”Quotient after division:”&lt;&lt;divide();}void main()

{ Arith a; a.setdata(10,2); a.display();}

The member functions add(), subtract(), multiply() and divide() are declared without
specifying

any access which means that they are by default private members. The member functions
setdata()

and display() are declared as public. The private members are not accessible outside the class
and

these members are called only within functions within the class. It is not possible to call the
private

member functions with respect to objects. i. e as a.add() or a.divide() etc,.

Static data members It is possible for a class member variable to be declared as static. When
a member variable is declared as static, only one copy of that variable exist, no matter how
many

objects of that class are created. Each object shares that one variable. For a normal variable, a
new

copy of the variable is created each time an object is created and that copy is accessible only
by

that object. There is only one copy of the static member variable and all objects of its class
share it.

A static class member is a global variable that has its scope restricted to the class in which it

is declared. When you declare a static member within a class, you are not defining it. The
definition

has to be provided outside the class. To define it, the static member variable has to be re-
declared

using the scope resolution operator to identify which class it belongs to. All static member

variables are initialized to zero, by default. However, it is possible to give the variable an
initial value

you like. The principal reason the static member variables are supported by C++ is to avoid
the

need for global variables. The classes that use global variables almost violate the
encapsulation principle.

Static member functions Like static data members, static member functions can also be
defined.

A static member function has the following properties :

 A static function can access only static members declared in the same class

 A static function can be called using the class name as

Class_name :: function_name();

It is also possible to invoke static member functions using objects.

Example:

#include&lt;iostream.h&gt;

class test

int code;
static int count;

public:

void setcode()

void showcode()

static void showcount()

};

int test :: count=0;

void main()

test t1, t2;

t1.setcode();

t2.setcode();

test :: showcount();

test t3;

t3.setcode();

test::showcount();

t1.showcode();

t2.showcode();

t3.showcode();

}
Output:

Count : 2

Count : 3

Object number : 1

Object number : 2

Object number : 3

The static function showcount() displays the number of objects created till that moment. A

count of the number of objects created is maintained by static variable count.

Array of Objects Objects are variables that have the same capabilities and attributes as any

other type of variable. Therefore, it is perfectly acceptable for objects to be arrayed. The
syntax for

code = ++count;

cout&lt;&lt;”Object number:”&lt;&lt;code;

cout&lt;&lt;”count:”&lt;&lt;count;

declaring an array of objects is exactly like that used to declare an array of any other type of

variable. Further arrays of objects are accessed just like arrays of other types of variables.
Example:

#include&lt;iostream.h&gt; class Employee

{ int eno; char name[30]; float basicpay; float hra; float cca; float

ma; float it; float pf;public : void getdata(); float grosspay(); float deduction();

{ cin&gt;&gt;eno; cin&gt;&gt;name; cin&gt;&gt;basicpay;}

float Employee :: grosspay()

{ hra = basicpay * .03; cca = basicpay * .02; ma = basicpay *.01;

{ pf = basicpay * .03; it = basicpay *.4; return(pf + it);}float Employee :: netpay()

{ return(grosspay() – deduction());}void Employee :: display()


{ cout&lt;&lt;”Employee number :”&lt;&lt;eno; cout&lt;&lt;”Employee
name :”&lt;&lt;name;

float netpay();} ;void Employee :: getdata()

return(basicpay + hra +cca + ma);}float Employee :: deduction()

cout&lt;&lt;”Basic pay: “&lt;&lt;basicpay; cout&lt;&lt;”Grosspay: “&lt;&lt;grosspay();

cout&lt;&lt;”Deductions: “&lt;&lt;deduction(); cout&lt;&lt;”Net pay :”&lt;&lt;


netpay();}void main()

e[i].display();}

{ Employee e[10]; for(int i= 1;i&lt;10;i++) e[i].getdata(); for(int i= 1;i&lt;10;i++)

10 employee objects are created as an object array e[10]. Each object is referred by
specifying the

array name with the subscript ie e[0] …e[9].

Friend functions There will be times when you want a function to have access to the private

members of a class without that function actually being a member of that class. For this
purpose,

C++ supports friend functions. A friend function is not a member of the class but still has
access to

its private members.

 A friend function is declared as a regular non member functions. The function’s prototype
is

included in the class declaration of the class for which it is a friend function. The prototype is

prefaced by the keyword friend.

 Since friend function is not a member of a class, it is not possible to call a friend function
by

using an object name and a class member access operator(a dot or arrow). Instead, friend

functions are called just like regular functions.

 Although a friend function has knowledge of the private elements of the class for

which it is a friend, it can only access them through an object of the class. Normally a friend

function has objects as its arguments.Example:

#include&lt;iostream.h&gt;class B;
class A

{ int num1;public : void setvalue(int i)

{ num1=i; }

friend void max(A o1, B o2);};class B

{ int num2;public: void setvalue(int i)

{ num2=i; }

friend void max(A o1, B o2);};void max(A o1, B o2)

{ if(o1.num1&gt;o2.num2) cout&lt;&lt;”Greatest number:”&lt;&lt;o1.num1; else

cout&lt;&lt;”Greatest number:”&lt;&lt;o2.num2;}void main()

{ A o1; B o2; o1.setvalue(10);

o2.setvalue(20); max(o1,o2); } The program tries to compare

the value in class A and the value in class B and tries to print the greatest number. It is
possible to

access the private member of class A and B within the function max, as it is a friend of both
the

classes. The function max() has arguments of type A and B. When the function is declared as
a

friend in class A for the first time, the compiler will not acknowledge the presence of class B
unless

its name is declared in the beginning as class B;This type of declaration is

called forward declaration.

Overloading Member functions

Member functions can be overloaded in the same method as other ordinary functions.

Overloading is nothing but one function is defined with multiple definitions with same
function name

in the same scope.

Example

#include&lt;iostream.h&gt;

#include&lt;conio.h&gt;
Class num

int a,b,c;

float c,d,e;

Public:

int add(int,int);

float add(float,float); void display();

};

int num::add(int x, int y)

int t;

T=x+y;

Return t;

float num::add(float x,float y)

float t;

T=x+y;

Return t;

Void num:: display()

cout&lt;&lt;add(2,3);//function call

cout&lt;&lt;add(2.3,1.3);//function call

}
Void main()

num n;

n.display();

getch();

In the above program the member function add is overloaded.

BIT FIELDS AND CLASSES

Bit fields provides exact amount of bits required for storage of values. If a variable is 1 or 0,

we need a single bit to store it. The number of bits required for a variable is specified by non-

negative integer followed by a colon.

To hold information we use the variables. The variables occupy minimum one byte for char

and two bytes for integer. Instead of using complete integers if bits are used, space of
memory can

be saved. Arrays of bit fields are not permitted. Also the pointer cannot be used for
addressing the

bit directly, although use of the member access operator ( -&gt; ) is acceptable. The unnamed
bit fields

could be used for padding as well as for alignment purposes.

1. Bits fields should have intearal type. A pointer array type is now allowed .

2. Address of the bit fields cannot be obtained using &amp; operator.

Example:

Class vehicle

unsigned type : 3;

unsigned fuel : 2;

unsigned model : 3;

};
the colon (:) in the above declaration tells to the compiler that bit fields are used in the class
and the

number after it indicates how many bits are required to allot for the field.

CONSTRUCTORS

So far, we have used member functions to provide initial values to the private member

variable. These member functions are called after objects are created and cannot be used to

initialize the member variables at the time of creation of objects. C++ provides a special
member

function called constructor. A class’s constructor is called each time an object of that class is

created. Thus, any initializations that need to be performed on an object can be done
automatically

by the constructor function.

A constructor function has the same name as the class of which it is a part and has no return

type.

A constructor that accepts no parameters is called the default constructor. If no such

constructor is defined, then the compiler supplies a default constructor.

Example:

#include&lt;iostream.h&gt;

class myclass

{ int a;

public :

myclass();

void show();

};

myclass ::myclass()
{

cout&lt;&lt;”In_constructor”;

a = 15;

void myclass :: show(){

cout&lt;&lt;”value of a:”&lt;&lt;a;

void main()

myclass o1;

o1.show();

Output:

In_constructor

a:15

The value of a is initialized by the constructor myclass(). The constructor is called when the
object

o1 is created. An object is created when that object’s declaration statement is executed.

DESTRUCTORS

It is used to destroy the object that have been created by a constructor. Like a constructor, it

also has the same name as that of a class name, but it is preceded by a tilde(~).

For eg.

~integer()

{}

It has no arguments and does not return any value. It is also invoked implicitly by the
compiler

on exit from the program to clean up storage.


Example:

#include&lt;iostream.h&gt;

class samp

int a;

public:

samp()

cout&lt;&lt;&quot;object created&quot;;

a=10;

show()

cout&lt;&lt;a;

~samp()

cout&lt;&lt;&quot;Object destroyed&quot;;

};

void main()

samp s;

s.show();

}
Output:

Object created

10

Object destroyed

Characteristics of constructors and destructors

Constructors:

1. Constructor has the same name as the class name.

2. Constructor is executed when an object is declared.

3.Constructors have neither void nor return value.

4. The main function of constructor is to initialize objects.

5. Though constructors are executed implicitly they can be invoked explicitly.

6. Constructor can have default can be overloaded.

7. The constructor without arguments is called as default constructor.

Destructors:

1. Destructor has the same name as that of the class it belongs to and precede by ~ (tilde)

2. Like constructor, the destructor does not have return type and not even void.

3. Constructor and Destructor cannot be initialized

4. Destructors can be virtual, but constructors cannot.

5. Only one destructor can be defined in the destructor. Destructor does not have any
arguments.

6. The destructors neither have default values nor can be overloaded.

7. Programmers cannot access addresses of constructors and destructors.

Calling constructor and destructor

The compiler automatically calls the constructor and destructor. We can also call the
constructor and

destructor in the same fashion as we call the normal user defined function.

To call constructor
Constructor name arguments semicolon.

Example

Num();

To call destructor

Object operator ::~ destructor semicolon

Example

Num x;

x.::~num();

Constructor and destructor with static members

Every object has its own set of data members. When a member function is invoked, only one

copy of data member of calling object is available to the function. Of the member variable is
declared

as static only one copy is created for entire class. All objects access the same copy of static
variable.

Example:

Class num

Static int n;

Public:

Num()

Cout&lt;&lt;”Constructor called”;

n++;

cout&lt;&lt;n;

~num()

Cout&lt;&lt;”Destructor called”;
-- n;

Cout&lt;&lt;n;

};

Int num::n=0;

Void main()

Clrscr();

Num a,b,c;

Getch();

Output:

Constructor called1

Constructor called2

Constructor called3

Destructor called2

Destructor called1

Destructor called0

Suggested Question:

1 What is class?

2 How is a member function of a class defined?

3 What are objects?

4 What is friend function?

5 Write the purpose of constructor.


6 What is destructor?

7 What is parameterized constructor?

8 Define a class to represent a book. Include the following data members:

Book name,Author name,Year of publishing, Accession number

9 write a function to find largest among three given numbers using call by

reference using class.

10 Explain about copy constructor with suitable example.

11 How will you create a constructor with default arguments? Explain with

suitable example.

12 State how many methods are available to call the constructor and

explain each of them with suitable example.

13. Define a class to represent a student . include the following members

data members name , rollno , marks in 3 subjects, total ,grade

function members

i. to assign values to name , rollno , marks.

ii. To compute total

iii. To assign grade for a student

iv. Display all

Write the main program to do the same.

UNIT III
OPERATOR OVERLOADING

Operator overloading is one of the exciting features of C++ language. C++ tries to make

the user-defined data types behave in much the same way as the built in types. C++ permits
to add two

variables of user-defined types with the syntax that is applied to basic types. This means that
C++ has
the ability to provide the operators with a special meaning for a data type. The mechanism of
giving

such special meanings to an operator is known as operator overloading.

Semantics of an operator can be extended, cannot change its syntax, the grammatical rules its
use such

as the number of operands, precedence and associativity. When an operator is overloaded, its

original meaning is not lost i.e. + operator can add two complex numbers or any two integers.

Defining Operator Overloading:-

To define an additional task to an operator, it must be specifies what it means in relation to


the

class to which the operator is applied. This is done with the help of a special function called
operator

function, which describes the task. The general form of an operator function is

Return type class name :: operator op(arg-list)

function body

where return type is the type of value returned by the specified operation and op is the
operator being

overloaded. The operation is preceded by the keyword operator, operator operation is the
function name.

Operator functions must be either member functions or friend functions. The process of
overloading

involves the following steps:

1. First, create a class that defines the data type that is to be used in the overloading
operation.

2. Declare the operator function operator op( ) in the public part of the class. It may be either
a member

function or a friend function.

3. Define the operator function to implement the required operations.

A basic difference between operator function as a member function or friend function is that
a friend function will
have only one argument for unary operators and two arguments for binary operators, while a
member function has

no arguments for unary operators and only one for binary operators. This is because the
object used to invoke the

member function is passed implicity and therefore is available for the member function. This
is not the case with

friend functions.

Overloaded operator functions can be invoked by expressions as

In case of unary operators

In case of binary operators

Overloading Unary Operators : -

A minus operator , when used as a unary takes just an operand. When applied to an object , it
should

change the sign of each of its data members.

Operator function as member function to overload minus operator.

op x or x op // Interpreted as operator op (x) for friend functions.

x op y // Interpreted as x.operator operation(y) for member functions.

//Interpreted as operator operation(x,y) for friend functions

Void space :: operator – ( )

x = - x;

y = - y;

z = - z;

main( )

space s;

s.getdata( 10, -20,30);

-s;

s.display ( );
}

Here function operator –( ) takes no argument the function changes the sign of data members
of

S. The statement

S2 = - S1 will not work because the function does not return a value.

Operator function as a friend function to overload minus operator.

Friend void operator – ( space &amp;s );

Void operator – ( space &amp;s )

s.x = -s.x;

s.y = -s.y;

Pass by value does not work because only a copy of the object that activated the call is
passed to

operator – ( ). The changes made inside the operator function will not reflect in the called
object.

Overloading Binary Operators : -

To overload the + operator which accepts two operands is as

C=A+B;

For eg;

complex complex :: operator + ( complex c )

complex temp;

temp.x = x + c.x;

temp.y = y + c.y;

return(temp);

In the above case, function receives a single argument and returns an object, both of type
complex. The
invoking statement for the above operator function is

c3 = c1 + c2;

The function is expected to add 2 complex values, but receives only one argument. So the

statement is equivalent to

c3 = c1.operator + (c2);

Therefore, in the operator+() function, the data members of c1 are accessed directly and the
data

members of c2(passed as an argument) are accessed using the dot operator.

temp.x = x + c.x;

where c.x refers to the object c2, x refers to the object c1. temp.x is the real part of the result.
The

function returns temp which is of object c3.

As a rule, the right hand operand is passed as an argument, whereas the left hand operand is
used to

invoke the function.

Overloading Binary Operators using Friends :-

Friends may be used in the place of member functions for overloading a binary operator. The

difference is that friend requires 2 arguments to be passed explicitly whereas the member
function needs

just one.

The modification that are to be made are :

- Replace the member function declared by the friend function declaration.

Friend complex operator + (complex, complex);

- Redefine the operator function as follows

complex operator + (complex a , complex b)

return complex (( a.x + b.x ), ( a.y + b.y));

}
- The statement, C3 = c1 + c2 is interpreted as

c3 = operator + (c1 , c2);

Friends are used in cases where two different types of operands for a binary operator such as
an

object and a built in type.

For eg:-

A = B + 2 ; or A = B * 2;

This does not work with operator function as member functions because the left hand
operand

which is responsible for invoking the member function should be an object of the same class.
Objects

need not be used to invoke friend functions and so the built in data type is the left operand
and the

object is the right.

Manipulations of Strings using operators :-

Strings are manipulated using strings and not operators. This becomes a limitation to the
string

manipulation. To avoid these limitations, C++ permits us to create our own definitions of
operators that

can be used to manipulate the strings very much similar to decimal numbers.

For eg;-

string 3 = string1 + string2;

If (string1 &gt;= string2 )

string = string1;

Strings can be defined as class objects which can then be manipulated lke the built in

types. Since the strings vary in size, new is used to allocate memory for each string and a
pointer

variable to point to the string array. So two string objects are created that can hold the pieces
of

information namely, the length and location for string manipulations.


Class string

char *p;

int len;

public:

-- -- -- -- -- -

-- -- -- -- -- -

int operator &lt; = (const string &amp;s, const string &amp;t )

int m = strlen (s.p);

int n = strlen (t.p);

if (m &lt;= n )

return (1);

return(0);

string operator + (const string &amp;s, const string &amp;t)

string temp ;

temp.len = s.len + t.len;

temp.p = new char [temp.len + 1 ];

strcpy (temp.p,s.p);

strcat (temp.p, t.p);

return (temp);

Rules for Overloading :-

- Overloading can be done only on existing operators. New operators cannot be overloaded.

- The overloaded operator must have at least one user-defined type operand.
- The basic meaning should not be changed.

- Overloaded operators follow the syntax rules of the original operators..

- A few operator can not use friend function, but member function can do the same .

- Binary operators takes one argument in the case of member function and two

arguments in the case of friend function.

- When using binary operators overloaded through a member functon, the left hand operand

must be an object.

- Binary operators such as + , - ,* and / must explicitly return a value.

- There some operators that cannot be overloaded.

Type Conversions:-

Constants and variables of different types are mixed in an expression to which certain rules
are

applied as per rules in C. An assignment operation also causes the automatic type conversion.
Compiler

does not support automatic type conversion for user-defined data types.

Three types of conversions are possible:

- conversion from built in to class type.

- conversion from class to built in type.

- conversion from one class to another class type.

Basic to Class type:-

Constructors are used for this type of conversion. This constructor takes a single argument
whose type is

basic type to which it is converted. The left hand operand of = operator is always a class
object.

The constructor was used to built a string type object from a char type array.

string :: string ( char *a)

length = strlen (a);


p = new char [length +1];

strcpy (p,a);

This constructor can be used for conversion from char * type to string type.

string s1, s2;

char* name1 = “IBM PC”;

char*name2 = “computers”;

s1 = string (name1);

s2 = name2;

In the above statement for converts name1 from char* type to string type and then assigns the

string type values to the object s1.

Class to Basic type :-

The constructor does not support the conversion from class to basic type. This conversion is
made

possible by an overloaded casting operators. The syntax is

operator typename( )

-- -- -- --

-- -- -- --
function statement

This converts the classtype to typename.

vector :: operator double ( )

double sum = 0;

for (int i =0; i&lt; size ; i++)

{
sum = sum + v [ i] * v [i];
}

return sqrt(sum);
}

This function converts a vector to double scalar magnitude. The costing operator function

should satisfy the following conditions.

- It must be a class member.

- It must not specify a return type.

- It must not have any arguments.

This being a member function, it is invoked using an object and the values used for
conversion

belongs to the object that invoked the function.

If a string is to be converted to char*, then

String :: operator char*( )

return(p);

Obj X = Obj Y

One Class to Another Class type :-

ObjX is an object of class X and ObjY is an object of class Y. The class Y type data is
converted to

class X type data and then the converted value is assigned to objX . Y is the source class and
X is the

destination class.

depending upon the location of type-conversion function in the source class or destination
class.

Casting operator function

Converts the class object of which it is member to a typename. The typename may be built in

type or user-defined one. In class of conversions between objects, typename refers to the
destination

class. Therefore, when a class needs to be converted, a casting operator function can be used
in source
class. The conversion takes place in the source class and the result is given to the destination
class.

A single argument constructor function serves as an instruction for converting the argument’s

type to the class type of which it is member. This implies that the argument belongs to the
source class

and is passed to the destination class for conversion.

If the conversion is done using the conversion function, then the typename ( ) becomes the

destination class if it is done using a single argument constructor, then, the argument belongs
to the

source class and is passed to the destination class for conversion.

Operator return type

In last few examples we declare the operator () of void types i.e., it will not return any value.
However,

it is possible to return value and assign to its other objects of the same type. The return value
of the

operator is always of the class type, because operator overloading is only for objects.

Note: An operator cannot be overloaded for basic data types. Hence , if the operator returns
any

value, it will always of the class types.

Consider the following program

#include&lt;iostream.h&gt;

#include&lt;conio.h&gt;

Class plusplus

private:

int num;

public:

Conversions can be made possible by either a constructor or a conversion function

operator typename ()
plusolus()

num = 0;

Int getnum()

return num;

Plusplus operator ++(int)

Plusplus tmp;

num = num + 1;

temp.num= num;

return tmp;

Void main()

clrscr();

plusplus p1,p2;

cout&lt;&lt;”\n p1 = “&lt;&lt;p1.getnum();

cout&lt;&lt;”\n p2 = “&lt;&lt;p2.getnum();

p1=p2++;

cout&lt;&lt;endl&lt;&lt;”p1 = ”&lt;&lt;p1.getnum();

cout&lt;&lt;endl&lt;&lt;”p12= ”&lt;&lt;p2.getnum();

p1++;

cout&lt;&lt;endl&lt;&lt;”p1 = ”&lt;&lt;p1.getnum();

cout&lt;&lt;endl&lt;&lt;”p12= ”&lt;&lt;p2.getnum();

Output:

P1 = 0

P2 = 0

P1 = 1

P2 = 1

P1 = 2

P2 = 1
Explanation: in the above program, class plusplus is declares with one private integer num.
the class

constructor initializes the object with zero. The member function getnum() returns current
value of

variable num. the operator ++() is overloaded and it can handle as a postfix increment of the
objects. In

case of prefix increment it will flag an error.

The p1 and p2 are objects of the class plusplus. The statement p1 = p2++, first increments the

value of p2 and then assigns it to the objects p1. the value displayed will be one for the
objects. The

object p1 is increased. This time the value of object displayed will be two and one.

Overloading With Friend Functions

Friend functions are more useful in operator overloading. The difference between member

function and friend function is that the member function takes argument explicitely, where as

friend function needs the parameters to be explicitly passed.

The syntax of operator overloading with friend function,

friend return-type operator operator-symbol(variable1,variable2)

statement1;

statement2;

Example program

#include&lt;iostream.h&gt;

#include&lt;conio.h&gt;

class complex

float real,img;

public:

complez()

real=img=0;

complex(float r, float i)
real =r;

img=i;

friend complex operator –(complex c)

c.real= -c.real;

c.img=-c.img;

return c;

void display()

cout&lt;&lt;”\n real :”&lt;&lt;real;

cout&lt;&lt;”\n img :”&lt;&lt;img;

Void main()

clrscr();

complex c1(1.5,2.5);

c1.display();

c2= -c1;

cout&lt;&lt;”\n AFTER NEGATION:”;

c2.display();

Output

real = 1.5

img = 2.5

AFTER NEGATION

real = -1.5

img = -2.5

INHERITANCE

Reusability is another important feature of OOP. The concept of reusability saves time and

money, reduces frustration and increase reliability. The C++ classes can be reused in several

ways. A new class can reuse the existing class. This is made possible by the concept of
inheritance.
The mechanism of deriving a new class from an old one is called inheritance. The old class is

called the base class and the new class is called derived class.

Inheritance is of different types.

Single inheritance:

A derived class with only one base class is called single inheritance.

A derived class with more than one base class is called multiple inheritance.

A derived class derived from another derived class is called multilevel inheritance.

The properties of class derived to more than one class is called hierarchical inheritance.

Defining Derived Classes

The derived class is defined by specifying its relationship along with the base class.

Multiple inheritance :

Multilevel inheritance:

Hierarchical inheritance:

For Eg.,

The syntax for defining a derived class is

class derived-classname : visibility-mode base-classname

-- -- //members of the derived class

-- --

};

class base : private derived

-- -- //members of derived

The visibility-mode can be either private or public. The derived class can be inherited
privately or
publicly from the base class. When the derived class is inherited privately from the base class
then the

public members of the base class will become private members of the derived class. The
objects of the

derived class cannot access them. If the derived class is inherited publicly from the base class
then the

public members of the base class become public members of the derived class and thus
accessible to the

objects of the derived class. In both the cases, the private members of the base class cannot
be inherited

and therefore they can never become members of the derived class.

For eg.,

class base

int a; //not inheritable

public:

int b;

void getdata();

};

class derived : public base

int c;

public:

void display();

};

main()

derived objd;

objd.getdata();
objd.display();

In the above example, the derived class can access only public members of base class, the
data

member b and the member function getdata(), but they cannot access the data member a
because a is not

inherited.

If the derived class was derived privately, for eg.

class base

int a; //not inheritable

public:

int b;

OBJECT ORIENTED PROGRAMMING WITH C++ UNIT III

void getdata();

};

class derived : private base

int c;

public:

void display();

};

main()

derived objd;

objd.getdata(); // Not possible


objd.display();

In case of the private inheritance, the public members of the base class become the private

members of the derived class. As a result, the public members of the base class cannot be
inherited, in

turn the objects of derived class cannot access the members of the base class. So members of
the base

class can be accessed using the public member functions of the derived class. A simple
modification to

the above program can solve this program. The member function getdata() can be called with
the

display() of the derived class.

class base

int a; //not inheritable

public:

int b;

void getdata();

};

class derived : private base

int c;

public:

void display()

getdata();

};

main()
{

derived objd;

objd.display();

Making a Private Member Inheritable:

C++ provides a third visibility modifier named protected whose visibility is neither
completely

private or public. A private member cannot be inherited at all to a derived class, but a public
member

can be inherited and be accessed by all other functions of the program. But, a protected
member is

accessible by the member functions within its class and any class immediately derived from
it. It cannot

be accessed by functions outside these two classes. When the protected member of the base
class is

inherited in public mode, then it becomes protected in the derived class too and that can be
inherited

further. But, when inherited in private mode, it becomes a private member of the derived
class and it

cannot be further inherited.

Visibility of inherited members

Visibility Public derivation Private derivation

Private Not inherited Not inherited

Base class Derived class visibility

Protected Protected Private

Public Public Private

Multilevel Inheritance

A class derived from another derived class. The class A serves as a base class for the derived
class B

which in turn serves as a base class for the derived class C.


Base Class Grandfather

Intermediate Base Father

Class

Derived Class Child

Multilevel Inheritance

A derived class with multilevel inheritance is declared as follows:

class A

class B : public A

class C : public B

{ };

{ };

{ };

Consider an example, The test results of students are stored in 3 different classes. Class
student

stores the rollnumber and name, class test stores the marks obtained in two subjects and class
result

contains the total marks obtained in the test. The class result can inherit the details of marks
obtained in

the test and roll number of students through multilevel inheritance.

#include&lt;iostream.h&gt;

class student

protected :

int roll_number;

char name[20];
public :

void get_number(int a,char nm[20])

roll_number=a;

name=nm;

void display_number()

cout &lt;&lt;roll_number;

cout&lt;&lt;name;

};

class test :public student

protected :

int mark1,mark2;

public :

void get_marks(int m1,int m2)

mark1=m1;

mark2=m2;

void display_marks()

cout &lt;&lt; mark1;

cout&lt;&lt; mark2;
}

};

class result : public test

protected :

int total;

public :

void display_total()

total = mark1 + mark2;

display_number();

display_marks;

cout &lt;&lt; total;

};

main()

result object;

object.get_number(101,”Anu”);

object.get_marks(90,80);

object.display_total();

Multiple Inheritance

A class can inherit the attributes of two or more classes. This type of inheritance is called

multiple inheritance.

B-1 B-2 B-3

Multiple Inheritance
Syntax of a derived class with multiple base class is as follows:

class D : visibility mode B-1, visibility mode B-2,…..

…….

…..

};

where visibility may be public or private. The base class are separated by commas.

For eg.

class M

protected :

public :

int m;

void get_m(int a)

m=a;

};

class N

protected :

public :

int n;

void get_n(int b)

11

OBJECT ORIENTED PROGRAMMING WITH C++ UNIT III


{

n=b;

};

class P : public M, public N

public :

void display()

cout&lt;&lt;m*n;

};

main()

P objp;

objp.get_m(10);

objp.get_n(5);

objp.display();

Hierarchical Inheritance

Another interesting application of inheritance is to use it as a support to the hierarchical


design of

a program. Many programming problems can be cast into a hierarchy where certain features
of one level

are shared by many others below that level

Students

Arts Engineering Medical

Mech. Elec Civil


Hybrid Inheritance

Some situations do arise where two or more type of inheritance are used to design

a program. The following example gives an example of two types of inheritance being used.
I.e.

multilevel and multiple inheritance.

student

test sports

result

Virtual Base Classes

In a situation where all the types of inheritances such as multilevel and multiple are involved,

the child may have two direct base classes ‘parent1’ and ‘parent2’ which themselves have a
common

base class ‘grandparent’. The ‘child’ inherits the traits of ‘grandparent’ via two separate
paths. The

‘grandfather’ is sometimes referred to as indirect base class. As result, child inherits the
properties of

the two parent classes and thus it contains duplicate copies of the parent. In other words the
child

inherits the traits of the grandparent via two separate paths.

12

OBJECT ORIENTED PROGRAMMING WITH C++ UNIT III

Grandparent

Parent 1

Parent 2

Child

The duplication of inherited members due to these multiple paths can be avoided by making
the

common base class as virtual base class while declaring the direct or intermediate base
classes

class A //grandparent
{-- -- -- -- -};

class B1 : virtual public A //parent1

{-- -- -- -- -};

class B2 : public virtual A //parent2

{-- -- -- -- -};

class C : public B1,public B2

{-- -- -- -- -}; //only one copy of A is inherited

Abstract Classes:

An abstract class is one which is not used to create objects. It is designed to act as a base
class

upon which other classes can be inherited.

SUGGESTED QUESTIONS

1. Define operator overloading?

2. Explain the concept of unary operator overloading?

3. Explain about the operator return types?

4. Give a sample program with examples of binary operator overloading?

5. Explain the concept of friend function with respect to operator overloading?

6. List the rules for operator overloading?

7. Write briefly about the concept of inheritance?

8.List the types of inheritance and explain in detail?


9. Explain about virtual base class?

UNIT IV
4.1.1. POINTERS, VIRTUAL FUNCTIONS AND POLYMORPHISM:

Polymorphism is the technique in which various forms of a single function can be

defined and shared by various objects to perform the operation. The concept of

polymorphism is implemented using the overloaded functions and operators.

Polymorphism can be of two types - compile time and runtime polymorphism


Compile time polymorphism

The overloaded member functions are selected for invoking by matching

arguments, its type and number. The compiler knows this information at compile time

itself. It is called as early binding or static binding or static linking. Early binding means

that an object is bound to its function call at compile time. Function overloading and

operator overloading uses the concept of compile time polymorphism.

Example :

class first

public:

void display ()

};

class second : public first

int d;

-- -- -- -- - // base class member function

C++ Page 2 Unit IV &amp; V

{ int k ;

public :

void display ()

in the above program , base and derived classes have the same member

function display( ) this is not overloaded function because their prototype is same and

they defined in different classes.

Run time polymorphism:


The function are linked to the function call at only at run time. It is otherwise

termed as late binding because the function is linked with a particular class much later

after the compilation. It is also known as dynamic binding because the selection of

appropriate function is done dynamically at run time. C++ supports a mechanism

known as virtual function to achieve runtime polymorphism.

Example :

class first // base class

public:

virtual void display ()

};

class second : public first // derived class

public :

virtual void display ()

in the above program , base and derived class have the same member function

display ( ) preceded by the key word virtual. The various forms of virtual functions in

base classes are dynamically bound.

-- -- -- -- -- -- -- //derived class member function

int d;

-- -- -- -- - // base class member function

int k ;
-- -- -- -- -- -- -- //derived class member function

Polymorphism

Compile time

Polymorphism Runtime

Polymorphism

Function

Overloading

Operator

Overloading

Virtual

functions

C++ Page 3 Unit IV &amp; V

4.1.2. Pointer to derived class objects:

inheritance provides the hierarchical relationship between two objects and

indicates the shared properties between them . pointers can be declared to point to

based or derived classes. A pointer to base class object can point to objects of

derived classes whereas a pointer to derived class object cannot point to objects of

base class object.

Example :

// program to access members of base and derived classes using pointer objects

of both classes

# include &lt;iostream.h&gt;

#include&lt;conio.h&gt;

class w

protected :

int x;
public:

w(int k) {x=k;}

void show( )

cout &lt;&lt;”\n in base class w “;

cout &lt;&lt;”\n x = “&lt;&lt;x;

};

};

class y : public w

protected:

int z;

public :

y(int j,int k):w(j)

z=k;

void show ( )

cout &lt;&lt;”\n in class y “;

cout&lt;&lt;”\n x=”&lt;&lt;x;

cout &lt;&lt;\n y=”&lt;&lt;z;

};

class p :public y

{
public :

int q;

};

void main()

clrscr();

w *b;

b =new w(20);b -&gt; show();

delete b;

b =new y(3,2);

b- &gt;show( );

((y * b)-&gt; show( );

delete b;

C++ Page 4 Unit IV &amp; V

y r(3,4);

y *d=&amp;r;

d-&gt;show( );}

In the above program class w is base class. Y is derived form w. p is derived

from y. Here the type of inheritance is multi level inheritance. The variable *b is a

pointer object of class w. the statement b= new w( 20) creates a nameless object and

returns its address to class w. the show ( ) function is invoked by the point b. here the

show ( ) function of base class w is invoked. Using delete operator the pointer b is

deleted.

The statement b= new y(3,2) creates nameless object of class y and assigns its

address to base class point b. here note that the object of base class and it is initialized

with address of derived class object. Again pointer b invokes the function of derived

class y , following statement is invoked


(( y *b ) -&gt; show(); type casting Is used. The statement y r(3,4) creates object r

of class y. the statement y *d = &amp;r; declares pointer object d of derived class y and

assigns the address of r to it. The pointer object d invokes the derived class function

show( ); Here, pointer of class w can point to its own class as well as its derived class.

The pointer class y can point to its own and derived class but not the base class.

4.1.3. Virtual Functions.

An essential requirement of polymorphism is the ability to refer to objects without

any regard to their classes. This necessitates the use of a single pointer variable to

refer to the objects of different classes. So, the pointer to a base class is used to refer

all the derived objects. But, when a base pointer is used and it contains the address of

a derived class, always executes the function in the base class. So the concept of

polymorphism is not used. It is achieved using what is known as ‘virtual’ functions.

When the same function name used in both the base and the derived classes,

the function in base class is declared as virtual using the keyword virtual preceding its

normal declaration. When the function is made virtual, C++ determines which function

to use at run time based on the object pointed to by the base pointer, rather than the

type of the pointer . Thus by making the base pointer point to different objects different

versions of the virtual function can be executed.

Example:

class base

int a;

public:

void display()

}
virtual void show()

cout&lt;&lt;a;

cout&lt;&lt;”base”;

};

class derived

public:

int b;

void display()

cout&lt;&lt;”Derived”;

C++ Page 5 Unit IV &amp; V

void show()

cout&lt;&lt;b;

};

void main()

base *ptr;

base b;

ptr=&amp;b;

ptr-&gt;show(); //invokes base class show()

ptr-&gt;display(); //invokes base class display()


derived d;

ptr=&amp;d;

ptr-&gt;display(); //invokes base class display()

ptr-&gt;show(); //invokes derived class show() because base show() is virtual

//and also now the pointer ptr has the address of derived obj.

4.1.4. Rules for virtual functions

 Virtual members must be members of some class.

 They cannot be static members.

 They are accessed by using object pointers.

 A virtual function can be a friend of another class.

 constructors cannot be declared as a virtual, but destructors can be declared as

virtual.

 the virtual function must be defined in public section of the class. It is also

possible to define the virtual function outside the class. The virtual keyword is

used In the function declaration but not in the function declarator.

 it is possible to return a value from virtual function like other functions.

 arithmetic operation cannot be used with base class pointer.

 A virtual function in a base class must be defined though it is not used.

 virtual constructors is not possible but virtual destructors is possible.

 The operator keyword used for operator overloading also supports virtual

mechanism.

4.1.5. Array of pointers.

Polymorphism refers to late binding. Address of different objects can be stored in an

array to invoke function dynamically.

Example:
Class a

public :

virtual void show( )

cout&lt;&lt;”a\n”;

class b : public a

public:

void show() {cout &lt;&lt;”b\n”;}};

class c:public a

public :

void show()

C++ Page 6 Unit IV &amp; V

cout &lt;&lt;”c\n”;

class d : public a

public:

void show()

cout &lt;&lt;”d\n”;

class e: public a

public :

void show ( )

{cout &lt;&lt;”e”;

void main()

a a1; b b1; c c1; d d1; e e1;

a * pa[]={&amp;a1,&amp;b1,&amp;c1,&amp;d1,&amp;e1};

for (int j=0; j&lt;5;j++)

pa[j]-&gt;show();

4.1.6. Pure virtual functions

Function in the base class is declared virtual and it is redefined in the derived
class, but base class virtual function does not perform any task. So they are called as

‘do-nothing’ functions. It is defined as

virtual void display()=0;

These functions are also known as pure virtual functions. It is a function declared

in the base class with no definitions. A class with pure virtual function cannot be used to

create objects Such classes are called as abstract base classes.

Example:

Class first

protected:

public:

first(){b=10;}

virtual void display () =0;//puer function

class second: public first

public :

second( )

{d=20;}

void display()

cout &lt;&lt;”\n b= “&lt;&lt;b&lt;&lt;”d = “&lt;&lt;d;}};

void main()

first *p;

second s;

p= &amp;s;

C++ Page 7 Unit IV &amp; V

p-&gt;display();

4.1.7. Abstract classes

Abstract classes are like skeleton upon which new classes are designed to
assemble well designed class hierarchy. The well tested abstract classes can be used

and the programmer only extends them.

Example:

// The file abstract.h is an example of file containing abstract base class used for

debugging purpose.

Contents of “abstract.h” file

#include &lt;iostream.h&gt;

struct debug

virtual void show( )

cout &lt;&lt;”\n no function show( ) defined for this class”;

program to use abstract class for program debugging

#include “abstract.h”

#include &lt;constream.h&gt;

class x : public debug

int a;

public :

x(int j=0) {

void show ( ) {cout &lt;&lt;”\n in class x a =”&lt;&lt;a;}

class y: public debug


int b ;

public :

y(int k){b=k;}};

void main()

x x1(1);

y y1(5);

x1.show( );

y1.show( );

in the above program structure debug contains virtual function show(). This file is

#include in the above program. Class x and y are derived from class debug which is

defined in header file abstract.h. in function x1 and y1 are objects of class x and y

respectively. The statement x1.show( ) invokes the function show( ) and the value of

a is displayed. The object y1 also invokes function show( ). However the class y does

not have function show( ) hence , function show( ) of abstract base class is executed

which displays a warning message.

Points to remember on abstract classes:

1. Do not declare objects of abstract class type.

2. An abstract class can be used as a base class.


C++ Page 8 Unit IV &amp; V

3. The derived class should not have pure virtual functions. objects of derived

classes can be declared.

4.1.8. Working of Virtual functions

1. Binding means link between a function call and the real function that is
executed when function is called.

2. When compiler knows which function to cal before execution, it is known as

early binding.

3. Dynamic binding means that the actual function invoked at run time depends

on the address stored in the pointer . in this binding, link between function call

and actual function is made during program execution.

4. The keyword virtual prevents compiler to perform early binding. Binding is


postponed until program execution.
4.1.9. Virtual functions in derived classes

When functions are declared virtual in base classes , it is mandatory to redefine virtual
functions in the derived class.

Example:

// program to define a virtual base class function in the derived class .also add new
member in the derived class.

#include <iostream.h>

#include <conio.h>

class a

public:

virtual void joy ( ) {cout <<endl<<”in joy of the class a”;}

};

clas b : public a

{
public :

void joy ( ) {cout <<endl<<”in joy of class b”;}

void virtual joy2 ( ) {

cout <<endl<<”in joy2 of class b”;}

};

void main()

{}

a *a1,*a2;

a a3;

b b1;

a1=&a3;

a1->joy( );

a2 ->joy( );}

4.1.10. Object slicing

Virtual function allow us to manipulate both base and derived objects using same
member functions with no modifications. Virtual function can be invoked using pointer or
reference. If we do so, object slicing takes place.

Example:

#include <iostream.h>

#include <constream.h>

class a{

public:

int a1 ;

a( ){a1=10;}};

class b : public a

public :
int b1;

b( )

{ a1=40;b1=30;}

};

void main( )

a x ; b y;

cout <<” a1= “<<x.a1;

x=y;

cout <<”now a1=<<x.a1;}

4.1.11. Constructors and Virtual functions

It is possible to invoke virtual function using a constructor. When a virtual function


invokes through constructor, the base class virtual function will not be called and instead of
this member function of the same class is invoked.

Example:

class b

int k;

public :

b( int l) {k=l;}

virtual void show ( )

cout <<endl<<”k = “<<k;}

};

class d : public b

{
int h;
public :
d (int m, int n):b(m)
{
h=n;
b * b1;
b1= this;
b1->show( );
void show( )
{
cout <<endl<<”h =”<<h;
}};
void main()
{
b b1(4);
d d1(5,2);
}
In the above program, the base class b contains a virtual function. In the derived class d
the same function is redefined. Both the base and derived classes contain constructors. In the
derived class constructor, a base class point *b1 is declared. We know that this pointer contains
address of object calling member function. Here, this pointer holds the address of object d1. the
pointer object b1 invokes function show( ). The derived class show ( ) function is invoked.

4.1.12. Virtual Destructors


The virtual destructor is implemented in the same way like virtual functions. Destructors
of derived and base classes are called when a derived class object addressed by the base class
pointer is deleted.
Example:
Class B{
Public:
B()
{cout <<endl<<”in constructor of class B”;}
virtual ~B ( ) {cout <<endl<<”in destructor of class B”;}
};
class D: public B
{
public :
D( ) {cout <<endl <<”in constructor class D “;}
~D ( ){ cout <<endl <<”in destructor class D “;}
};
void main( )
{
B *p;
P= new D;
Delete p;}

4.1.13. Destructors and Virtual Functions


When call to virtual function is made through the destructor, the redefined function of the
same class is invoked.
Example:
class B
{
public :
~B( ) {cout <<endl<<” in virtual destructor”;}
virtua void joy ( ) {cout <<endl<<” in joy of class B “;}
};
class D : public B
{
public:
~D ( )
{
B *p;
P=this;
p->joy ( );
}
void joy( ){ cout <<endl<<” in joy of class B “;}

}
};
void main( )
{
D x;;
}

In the above program, in destructor of the derived class function joy () is invoked. The member
function joy ( ) of the derived class is invoked followed by virtual destructor.

-------------------------------------------------------------------------------------------------------------------

5. WORKING WITH FILES:


Introduction
A file is a collection of related data stored in a particular area on the disk. Programs can
be designed to perform the read and write operations on these files.
A program involves either or both of the following kinds of data communication:
i) Data transfer between the console unit and the program.
ii) Data transfer between the program and a disk file.

The I/O system of C++ handles file operations which are very similar to the console input
and output operations. It uses file streams as an interface between the programs and the files. The
stream that supplies data to the program is known as input stream and the one that receives data
from the program is known as output stream. In other words, input streams extracts data from the
file and output stream inserts data to the file.

5.1 Classes for File Stream Operations:


The I/O system of C++ contains a set of classes that define the file handling methods.
They include ifstream, ofstream and fstream. They are derived from fstreambase class and from
the corresponding iostream.h class. These classes are designed to manage the disk files and are
declared in fstream.h and therefore this file should be included in any program that uses these
files.

The other file stream classes available are:


Class Contents
filebuf Its purpose is to set the file buffers to read and write.
It also contains close() and open() as members.

fstreambase Provides operations common to file streams. Serves as a base for fstream,
ifstream and ofstream classes. Contain open() and close() functions.
ifstream Provides for input operations. It contains open() with default input mode.
Inherits the functions get(),getline(), read(),seekg() and tellg() from
istream.

ofstream Provides for output operations. It contains open() as the default output
mode. It inherits put(),seekp(),tellp() and write() functions from ostream.

fstream Provides support for simultaneous input and output operations. Contains
open() as the default input mode. It inherits all the functions from istream
and ostream classes through iostream.

5.2 Opening and Closing a file:


A file should before being used should have the following things
 Suitable file name
 Data type and structure
 Purpose
 Opening method
The file name may be a string of characters containing two parts, a primary name and an optional
name.

Example:
Input.data
Test,doc
samp

A filestream can be defined using the classes ifstream, ofstream and fstream that are
contained in the header file fstream.h. The class to be used depends upon the purpose i.e., to read
data from the file or write data to it.
The two ways of opening a file are:

1.Using the constructor function of the class


2.Using the member function open () of the class

The first method is useful only one file in the stream is used and the Second method is used
when multiple files are to be managed using one stream.
Opening files using constructor

A constructor is used to initialize an object while it is created. In this case, a filename is used
to initialize the file stream object. The steps involved here are:
1. Create a file stream object to manage the stream using the appropriate class. That
is, the class ofstream is used to create the output stream.
2. Initialize the file object with the desired filename.

For e.g., if we want to open a file named “result”, then the command is
Program1
--------
--------
ofstream outfile(“results”); //open for output only
---------
---------

The above statement creates an object to manage the output stream. If the file result is to be
opened for reading only then the syntax could be of the form:
Program2
-------
-------
ifstream infile(“result”); //open for input only.
-------
-------
Since the same file is used for both the purposes, the connection with a file is closed
automatically when the stream object expires i.e, when the program terminates. In the above case
the ‘result’ file is closed when the program1 is terminated and the file is disconnected from the
outfile stream and the same process happens with the program2.
Instead of using two programs, for reading and writing of data, a single program to do both the
functions. The use of a statement

outfile.close(“result”);

disconnects the file ‘result’ from the output stream.

Program1:
ofstream outfile(“results”); //open for output only
-------
outfile.close(“result”);

ifstream infile(“result”); //open for input only.


-------
-------
intfile.close(“result”);

When a file is opened for writing only, then a new file is created if there is no file of that
name. If it already exists then the contents are deleted.

Example:
#include<fstream.h>
main()
{
ofstream out(“item”);
char name[30],n[30];
float price,p;
cout<<”Enter item name”;
cin>>name;
cout<<endl;
cout<<”Enter item cost”;
cin>>price;
cout<<endl;
out<<name<<”\n”;
out<<price<<”\n”;
out.close();

ifstream in(“item”);
in>>n;
in>>p;
cout<<”Item name = “<<n<<endl;
cout<<”Item cost = “<<p<<endl;
in.close();
}
Output:
Enter item name box
Enter item cost 55

Item name = box


Item cost = 55

Opening files using open()

The function open() can be used to open multiple files that use the same stream object. In
case of processing a set of sequential files a single stream object can be created and used to
open each file in turn. The syntax for the same is:
filestreamclass stream-object;
stream-object.open(“filename”);
For eg.
ofstream outfile; //create stream for output
outfile.open(“data1); //connect stream to data1
------
------
outfile.close(); //disconnect stream from data1
outfile.open(“data2); //connect stream to data2
------
outfile.close(); //disconnect stream from data2

Example:
#include<fstream.h>
main()
{
ofstream out1;
out1.open(“item1”);
out1<<”box”<<endl;
out1<<”ball”<<endl;
out1.close();

out1.open(“item2”);
out1<<”bell”<<endl;
out1<<”bat”<<endl;
out1.close();

ifstream in;
in.open(“item1”);
cout<<”Item1 file\n”;
char a[10];
while(in!=0)
{
in.getline(a,4);
cout<<a<<endl;
}
in.close();

in.open(“item2”);
cout<<”item2 file\n”;
while(in!=0)
{
in.getline(a,4);
cout<<a<<endl;
}
in.close();
}
Output:
Item1 file
Box
Ball
Item2 file
Bell
Bat

Detecting End-Of-File
Detection of the end-of-file is necessary for preventing any further attempt to read data from
file.
The syntax is:

while(fin);
fin is an ifstream object and it returns 0 if any error occurs in the file operation including the
end-of-file situation. Thus the while loop terminates when fin returns a value of zero on reaching
the end of file.

The end of file can be detected by another method such as:


If (fin1.eof() != 0){exit(1);}

eof() is a member function of ios class. It returns a non-zero value if the end of file is
encountered and a zero otherwise.

More about open() : file modes

The general form of open() with two arguments is

stream-object.open(“filename”,mode);

The mode parameter specifies the purpose for which the file is being opened. The mode
has default values for reading and writing such as

ios::in for ifstream meaning open for reading only.


ios::out for ofstream meaning open for writing only.

The file mode parameter can take one or more of such constants defined in the class ios.:

Parameter Meaning

ios::app append to end of file


ios::ate go to end of file on opening
ios::binary binary file
ios::in open file for reading only
ios::nocreate open fails if the file does not exist
ios::noreplace open fails if the file already exists
ios::out open file for writing only
ios::trunc delete contents of the file if its exists

The other points to be noted here are:


1. Opening a file in ios::out mode also opens it in ios::trunc mode by default
2. Both ios::app and ios::ate has the cursor at the end of the file when it is opened, but
the difference is that ios::app allows to add data at the end of the file only and the
ios::ate permits to add data or modify the existing data anywhere in the file.
3. The parameter ios::app can be used only with the files capable of output
4. Creating a stream using ifstream implies input and creating a stream using ofstream
implies output.
5. The fstream class does not provide a mode by default and therefore it should be
stated explicitly
6. The mode can combine two or more values using the bitwise OR operator. For e.g.
For eg.
fout.open(“data”,ios::app| ios::nocreate)
The above statement opens the file in the append mode but fails to open if does not
exist.

5.3 File pointers and their manipulations

Each file has two associated two pointers known as file pointers .
1. Input(get) pointer – Used for reading the contents of a given file location
2. Output(put) pointer - Used for writing to a given file location

Default actions

When a file is opened in read-only mode the input pointer is automatically set at
the beginning of the file. When opened in write-only mode then the existing contents of
the file are deleted and the output pointer is set at the beginning. If it is opened in append
mode then the pointer is at the end of the file so that new data can be added thereafter.

Functions for manipulation of file pointers

File stream classes support the movement of pointers using the following
functions:
seekg() – Moves the input pointer to a specified location.
For eg.
infile.seekg(10)
This statement makes the pointer to point to the 11 thposition because the numbering
starts from zero.
seekp() - Moves the output pointer to a specified location
tellg() - Gives the current posiition of the get pointer
tellp() - Gives the current position of the put pointer.
For eg.
ofstream fileout;
fileout.open(“hello”,ios::app);
int p= fileout.tellp();
In the above case, the output pointer is moved to the end of the file “hello” and p
represents the number of bytes in the file.

Specifying the offset

seekp() and seekg() have two arguments each, such as

seekg ( offset, refposition );


seekp ( offset, refposition );

Here offset represents the number of bytes the file pointer is to be moved from the
location specified by the parameter refposition. Refposition can be one of te following 3
constants,
1. ios::beg – start of the file
2. ios::cur – current position of the pointer
3. ios::end – end of the file

The seekg() function moves the associated file’s get pointer while seekp function
moves the associated file ‘s put pointer. fout is an ofstream object.

Seek call Action

fout.seekg(0,ios::beg); Go to the start


fout.seekg(0,ios::cur); Stay at the current position
fout.seekg(0,ios::end); Go to the end of the file
fout.seekg(m,ios::beg); Move to (m+1)th byte in the file
fout.seekg(m,ios::cur); Go forward by m bytes from the
current position
fout.seekg(-m,ios::cur); Go backward by m bytes from the
current position
fout.seekg(-m,ios::end); Go backward by m bytes from the
end

5.4 Sequential input/output operations:

The file streams classes support a number of member functions for performing the
input and output operations on files. One pair of functions, put() and get() are designed
for handling a single character at a time. Another pair of functions, write() and read() are
designed to write and read blocks of binary data.

put() and get() functions


The function put() writes a single character to the stream and get() reads a single
character from the stream.
Example:
#include<fstream.h>
#include<string.h>
main()
{
char string[30];
fstream file;
file.open(“text”,ios::in | ios::out); //input and output stream
for (int i=0;i<len;i++)
file.put(string[i]): //put a character to file
file.seekg(0) //get file pointer to start of the file
char ch;
while(file)
{
file.get(ch); //get char from file
cout<<ch; //display()
}
file.close();
}
5.5 Binary and ASCII files:
write() and read() function

These functions are used to handle the data in binary form. For eg., an integer
value 2094 takes 2 bytes to be stored in binary format and 4 bytes to be store in character
format.
Binary format is accurate because they are stored in exact internal representation.
There are no conversions while saving the data and therefore saving is much faster.
The functions take the following form:
infile.read((char *)&v,sizeof(v));
outfile.write((char*)&v,sizeof(v));
The first argument is the address of the variable v and the second argument is the
length of the variable in bytes. The address must be cast to type char* that is pointer to
character type.

Example:
#include <fstream.h>
#include <conio.h>
#includ e<string.h>
int main()
{
int num[]={100,105,120,120,115,155,200,255};
ofstream out;
out.open(“01.bin”);
out.write ((char *) &num,sizeof(num));
out.close();
for (int i=0;i<7;i++)
num[i]=0;

ifstream in;
in.open(“01.bin”);
in.read((char *)&num,sizeof (num));
for (i=0;i<7;i++)
cout<<num[i]<<”\t”;
return 0;}
Reading and writing class objects

The function write copies a character object from memory byte by byte with no
conversion. Here only the data members are written to the disk file and the member
functions are not.
Example
class student
{
char name[20];
int rollno;
char address [20];
public:
void read_data()
{
cout<<”Enter the name”;cin>>name;
cout<<”Enter the Rollno”;cin>>rollno;
cout<<”Enter the address”;cin>>address;
}
void display()
{
cout<<”Enter the name”;
cout<<”Enter the Rollno”;
cout<<”Enter the address”;
}
};
main()
{
student obj[4];
fstream file;
file.open(“students.dat”,ios::in|ios::out);
for (int i=0;I<4;i++)
{
obj[i].read_data[i]);
file.write((char *)&obj[i],sizeof(obj[i]));
}
file.seekg(0);
for (int i=0;I<4;i++)
{
file.read((char *)&obj[i],sizeof(obj[i]));
obj[i].display();
}
file.close();
}

5.6. RANDOM ACCESS OPERATION


Data files always contain large information and the information always changes.
The changed information should be updated otherwise the data is not useful. Thus to
update data in the file we need to update the data files with the latest information. To
update a particular record of data file it may be stored anywhere in the file but it is
necessary to obtain which location the data object is stored.
5.7 Templates:
Template provides generic programming by defining generic classes. In templates,
generic data types are used as arguments and they can handle a variety of data types.
A function that works for all c++ data types is called as generic function. It helps the
programmer to declare group of functions or classes. When used with functions they are
called as function templates. The templates associated with classes are called class
templates.
Need of templates:
1. It allows a single function or class to work with different types of data.
2. It overcomes all the limitations occurring while overloading function and allows
better flexibility to the program.
3. It provides portability.
Definition of class template:
Syntax:
Template declaration
Template class <T>
Class name_of_class
{
// class data and member function
}
in the above syntax first sentence tells the compiler that the following class declaration
can use the template data type.T is a variable that can be used in the class to define
variable of template type. Both template and class are key words.
The angle bracket is used to declare variables of type that can be used inside the class to
define variables of template type. One or more variables can be declare separated by
comma. Templates can be defined inside classes or functions. They must be global.

Tk;
Where k is the variable of type template. Instead of T we can use any alphabet .it is used
for defining template.
Example:
// program to show values of different data types using constructor and template.
#include <iostream.h>
#incldue<conio.h>
template <class T>
class data
{
public:
data (Tc)
{
cout <<’\n”<<”c =”<<”size in bytes :”<<sizeof (c);
}};
int main()
{
clrscr( );
data <char> h(‘a’);
data <int> i(100);
data <float> j(3.14);
return 0;
}
output :
c= A size in bytes:1
c=100 size in bytes :2
c=3.14 size in bytes :4

In the above program , the constructor contains variable of template T . The


template class variable can hold values of any data type. While declaring object The
data type is given before the object. The variable of template type can accept values of
any data type. Thus the constructor displays the actual values passed. The template c can
hold values of any data type. The values and space in bytes required by these variables
are displayed as the output.

Normal function template:


Normal function can use the template arguments. The difference between normal
and member function is that normal functions are defined outside the class. They are not
the member of any class and can be invoked directly without using object of dot operator.
The member functions are class members. They can be invoked using object of the class
to which they belong.
Norma template function declaration:
Template class <T>
Function name( )
{
// code
}
Example:
template <class T>
void show (T x)
{
cout <<”\n x =” <<x;}
void main( )
{
char c= ‘A’;
int i=65;
double d=65.98;
show(c ) ;
show(i);
show(d);
}

When we declare class data member of template type as well as the member
function of the class can also use the template member.for making member function of
template type ,no separate declaration is needed.

Example:
template <class T>
Class data
{T x;
public : data (T u)
{x=u;}
void show (T y)
{
cout <<”x =”<<x;
cout <<”y =”<<y<<’\n’;
}};
void main()
data <char> c(‘B’);
data <int> c(100);
data <double> d(18.23);
c.show(‘A’);
i.show(45);
d.show(54.34);
}

class templates with more parameter:


Classes can be declared to handle different data types. Such classes are known as
class templates. Theses classes are generic type and member functions of these classes
can operate on different data types. The class template may contain one or more
parameters of generic data type. The arguments are separated by comma with template
declaration. The declaration is as follows:
Template with multiple parameters:
template <class T1, class T2>
class name_of _class
{
// class declarations and definitions
}
example:
template <class T1 , clas T2>
class data
{
public :
data (T1 a, T2 b)
{
cout <<”\n a= “<<a <<”b =”<<b;
}};
int main()
{
data<int,float > h(2,2.5);
data<int,char > i(15,’c’);
data<float,int > j(2.5,50);
retun 0;
}
Function templates with more arguments:
syntax:
template <class T>
return _data_type function_name(parameter of tmeplate type)
{statement1;
statement2;
statement3;
}

example:
template < class A, class B, class C>
void show (A c,B i,C f)
{
cout <<”\n c= “<<c <<”i =”<<i<<”f =”<<f;
}
int main()
{
show(‘A’,8,2.5);
show(7,‘B’,2.5);
return 0;
}

Overloading of template functions:


A template function also supports overloading mechanism. It can be overloaded by
normal function or template function. while invoking these functions an error occurs if no
accurate match is met. No implicit conversion is carried out in parameters of template
functions. The compiler follows the following the following rules for choosing
appropriate function when program contains overloaded functions.

1. Searches for accurate match functions; if found it is invoked.


2. Searches for a template function through which a function that can be invoked
with accurate match can be generated; if found it is invoked.
3. Attempt normal overloading declaration for the function.
4. In case no match is found, an error will be reported.
Example:
Template <class A >
Void show (A c)
{cout <<”\n template variable c = “<<c;
}
void show (int f)
{cout <<”\n template variable f = “<<f;
}

int main()
{
show(‘A’);
show(7);
show(7.5);
return 0;
}

Member function template:


In the above program the template function defined were inline i.e. they were
defined inside the class . It is also possible to define them outside the class.
Example:
Template <class A >
Class data
{
public :
data(T c);
};
template <class T>
data <T> ::data (T c)
{cout <<”\n <<”c=”<<c;
}
int main()
{
data <char>h(‘A’);
data <int>i(‘100);
data <float>j(2.5);
return 0;
}
Class template with overloaded operators:
The template class permits to declare overloaded operators and member functions.
The syntax for creating overloaded operator function is similar to class template members
and functions.
Example :
Template <class T >
Class num
{
private :
T number r;
Public :
Num( )
{
number =0;}
void input ( )
{cout <<”\n enter a number “;
cin >>number;
}
num operator +(num)
{
void show ()
{
cout <<number;}
};
template <class T >
num <T> num <T> ::operator +(num <T> c)
{
num <T> tmp;
tmp.number =number +c.number;
return (tmp);}
void main()
{
num <int> n1,n2,n3;
n1.input();
n2.input ( );
n3=n1+n2;
n3.show();
}
Guidelines for templates:
Templates are applicable when we want to create type secure class that handle different
data types with same member functions.
The template classes can also be involved in inheritance. For example
template <class T>
class data :public base<T>
both data and base are template classes. The class data is derived from
template class base.
The template variables also allow us to assign default values. For example
template <class T , int x=20>
class data {
t num[x];
}
The name of the template class is written differently in different situations. While class
declaration , it is declared as follows:
class data { };
for member function declaration is as follows:
void data <T> ::show (Td){ }
where , show ( ) is a member function. Finally we can declare objects the class
name and specific data is specified before object name.
data <int> i1;
data <float > f1;
All templates arguments declared in template argument list should be used or definition
of formal arguments. If one of the template arguments is not used, the template will be
specious. Consider,
template <class T>
T show (void)
{
return x;
}
In the above example , the template argument T is not used as a parameter and the
compiler will report an error.
template <class T>
void show (int y)
{
T tmp;
}
In the above example, template type argument is not an argument. Possibly the
syntax will crash.
Template <class T, class S>
Void max(T &k)
{
S p;
}
The template variable S is not used. Therefore, complier time error is generated.
Difference between macros and templates:
Macro are not type safe. i.e., a macro defined for integer operation cannot accept float
data. They are expanded with no type checking.
It Is difficult to find errors in macros.
In case a variable is post incremented or decremented, the operation is carried out twice.
# define max(A) a+ ++a
void main( )
{
int a= 10, c;
c=max(a);cout <<c;
}
The macro defined in the above definition is expanded twice. Hence, it is a serious
limitation of macros. The limitation of this program can be removed using templates as
shown below:
template <class T>
T max (T k){
++k;
return k;}
void main( )
{
int a=10,c;
c= max(a);
cout<<c;}

5.8. Exception handling:


The two most common types of errors are
1. logic errors 2. syntax errors.
The logic errors occur due to poor understanding of the problem and solution procedure.
The syntactic errors arise due to poor understanding of the language itself. We can detect
these errors by using exhaustive debugging and testing procedures. Other than logic or
syntactic errors there some peculiar can arise. They are known as exceptions. Exceptions
are run time anomalies or unusual conditions that a program may encounter while
executing. The conditions are division by zero, array outside of its bounds, running out of
memory or disk space.

Steps involved in exception handling:


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)

Exception handling mechanism:


This mechanism is basically built upon three keywords, namely try, throw, and
catch the keyword try is used to preface a block of statements. (surrounded by braces)
which may generate exceptions. This block of statements is known as try block. When an
exception is detected, it is thrown using throw statement in the try block. A catch block
defined by the keyword catch catches the exception thrown by the throw statement in the
try block and handles it appropriately.
Syntax:
---------
--------
try
{
--------
throw exception; //block of statements which detects and throws on exception
…….
…….
}
catch (type arg) // catches exception
{
………. // block of statements that handles the exception
……….
……….
}
………..
………..
example:
#incldue<iostrem.h>
void main( )
{
int a,b;cout<<”enter values of a and b \n”;
cin>> a>>b;
int x= a-b;
try {
if (X!=0) {
cout <<”result (a/x) =”<<a/x<<”\n”;
}
else
{
throw (x);
}}
catch(int i)
{
cout<<”exception caught : x =<<x<<”\n”;
}cout <<”end”;
}

Throw mechanism:
When an exception that is desired to be handled is detected, it is thrown using the
throw statement in one of the forms:

throw(exception);
throw exception;
throw;
The operand object exception may be of nay type, including constants. It is also
possible to throw objects not intended for error handling.
When an exception is thrown, it will be caught by the catch statement associated with the
try block. That is , the control exists the current try block, and is transferred to the catch
block after that try block.
Throw point can be deeply nested scope within the try block or in a deeply nested
function call.
Catching mechanism:
Code for handling exception is included in catch blocks. A catch block looks loke
a fnciton definition and is of the form
Catch ( type arg)
{
// statements for managing exceptions
}
The parameter arg is optional. The catch statement catches an exception whose
type matches with the type of catch argument. When it is caught the catch block is
executed. If an exception is not caught, abnormal program termination will occur.

Multiple catch statements:


Syntax :
Try {
//try block
}
catch (type1 arg)
{
// catch block1
}
catch (type2 arg)
{
// catch block2
}
…………..
………….
…………..
catch (type n arg)
{
// catch block n
}

When an exception is thrown, the exception handlers are executed in order for an
appropriate match. The first handler that yields a match is executed. After executing the
handler, the control goes to first statement after the last catch block for that try. When no
match is found, the program is terminated. it is possible tat arguments of several catch
statements match the type of an exception . In such cases , the first handler that matches
the exception type is executed.
Example:
#include <iostream.h>
void test (int x)
{
try{
if (x ==1 ) throw x;
else if (x==0 ) throw ‘x’;
else if (x==-1) throw 1.0;
cout <<”end of try block”;
}
catch( char c)
{
cout <<”caught a character”;}
catch( int m)

out <<”caught an integer”;}

catch( double d)

cout <<”caught a double”;}


cout <<” end of try-catch system\n\n”;}
void main()
{
cout <<”testing multiple catches \n”
cout<<”x==1\n”
test(1);
cout<<”x==0 \n”
test(0);
cout<<”x== -1\n”
test(-1);
cout<<”x==2 \n”;
test(2);
}
output:
testing multiple catches
x==1
caught an integer
end of try – catch system
x==0
caught a character
end of try – catch system
x==-1
caught a double
end of try – catch system
x==2
end of try - block
end of try – catch system
Catch all exception:
In some situations, we may not be able to anticipate all possible types of execution
and therefore may not be able to design independent catch handlers to catch them. In such
situation we can force a catch statement to catch all exceptions instead of certain type
alone.
Syntax :
Catch( …)
{
//statements for processing all exceptions
}

Example:
void test (int x)
{
try{
if (x ==1 ) throw x;
if (x==0 ) throw ‘x’;
if (x==-1) throw 1.0;}
catch(…){
cout <<”caught all \n”;}
}
void main()
{
cout <<”testing generic catch \n”
test(-1);
test(0);
test(1);
}
output:
caught a exception
caught a exception
caught a exception

Rethrowing exceptions:
A handler may decide to rethrow the exception caught without processing it. In
such situation simple invoke throw without any arguments as shown below

throw;

This causes the current exception to be thrown to the next enclosing try/catch
sequences and is caught by a catch statement after that enclosing try block
example:
void divide( double x, double y)
{
cout <<: inside function”;
try{
if (y==0.0)
throw y;
else cout <<”division =”<<x/y;
}
catch (double)
{
cout <<”caught double inside the function\n”;
throw;
}
cout<< “end of function”;
}
int main()
{
cout <<” inside main”;
try{
divide(10.5,2.0);
divide(20.0,0.0);
}
catch(double)
{cout<<”caught double inside main\n”;
}
cout <<”end of main”;}

Specifying Exception:
It is possible to restrict a function to throw only certain specified exceptions. This
is achieved by adding a throw list clause to the function definition.
Syntax:
Type function (arg –list ) throw (type list)
{
……………
…………….
……………..
}
The type –list specify the type of exceptions that may be thrown. Throwing any
other type of exception will cause abnormal program termination. If we wish to prevent a
function from throwing any exception, we may do so by making the type-list empty. That
is, we must use throw( ); in the function header.
Example:
void test (int x) throw (int, double)
{
try{
if (x ==1 ) throw x;
else if (x==0 ) throw ‘x’;
else if (x== -1) throw 1.0;
cout<< “end of function block \n”;}
void main()
{
try{
cout <<”testing throw restrictions \n”
test(1);
test(0);
test(-1);
test(2);}
catch(char c)
{
cout <<”caught a character”;}

catch( int m)
{
cout <<”caught an integer”;}

catch( double d)
{
cout <<”caught a double”;}
cout <<” end of try-catch system\n\n”;}}
5.9. Working with strings:
Introduction to string :
A string is a sequence of characters. String can contain small, capital letters,
numbers and symbols. String is an array of character type. Each element of string
occupies a byte in memory. Every string is terminated by null (‘\0’) character.
Example :
Char a[6]=” India”
In the above example string contains 5 characters and the null character is also
appended as a last character. So that the size is given as 6.

Declaring an initializing string objects.


In c , we can declare strings as char text [10]; where as in c++ strings is declared as
object. The object declaration and initialization can be done using constructor in the string class.
String constructors:
Constructors - meaning
String( ); - produces an empty string
String (const char *text ); - produces a string object from a null ended string
String (const string & text);- produces a string object from other string objects.
Example:
String text; // declaration of objects
String text(“c++”; //using constructor without argument
Text1= text2; //using constructor with one argument
Text= “c++”+text1; //concatenation of string objects
Cin>>text; // reads string without space through keyboard
Getline (cin,text) / reads string with blank spaces
Example program to declare string objects. Perform assignment and concatenation operations
with the string objects.
#include<iostream.h>
#include <string.h>
void main()
{
string text;
string text1(“CPP”);
stringt text1(“oop”);
cout<<text1<<text2;
text=text1;
cout <<text;
text=text1+ “ “+text2;
cout <<text;
}
In the above program three objects text,text1,text2 of type string are declared. The text1
and text2 are initialized with “CPP” and “oop”. The object text is initialized with the contents of
beject text1 using operator “ =”.So that the value of text will be CPP. The again it is reassigned
with the joined value of object text1and text2. and display
CPP oop
Various member functions of class:
Function Use
Append( ) Adds one string at the end of another string
Assign( ) Assigns a specified part of the string
At( ) Access the characters located at given location
Begin( ) Returns a reference to the beginning of a string
Capacity( ) Calculates the total elements that can be stored
Compare( ) Compares two strings
Empty( ) Returns false if the string id not empty ,
otherwise returns true.
End( ) Returns a reference to the termination of string
Erase( ) Erases the specified character.
Find( ) Finds the given sub string in the source string
Insert( ) Inserts a character at a given location
Length( ) Calculates the total number of elements in the
string
Max_size( ) Calculates the maximum possible size of string
in a given system
Replace( ) Substitutes specified characters with the string
as specified
Resize( ) Modifies the size of the string as specified
Size( ) Provides the number of characters in the string
Swap( ) Exchanges the given string with another string

The operators used with arithmetic or comparison operations can be used with string objects.
They are
Operator Working
= Assignment
+ Joining two or more strings
+= Concatenation and assignment
== Equality
!= Not equal to
< Less than
> Greater than
>= Greater than or equal
<= Lesser than or equal
[] Subscription(used with array)
<< Insertion operator
>> Extraction operator
Handling string objects:
Using the member functions insert( ), replace( ), erase( ) and append ( ) we can modify
the string content.
Example:1
#include<iostream.h>
#include<string.h>
void main( )
{
string s1(“abchijk”);
string s2(“defg”);
cout <<s1;
cout<< s2;
cout <<”\n after insertion”;
s1.insert(3,s2);
cout <<s1;
cout s2;
}
output:
abchijk
defg

after insertion
abcdefghijk
defg

Example:2
#include<iostream.h>
#include<string.h>
void main( )
{
string s1(“abcdefg”);
cout <<s1;
cout <<”\n after replace( )”;
s1.repalce(1,3,”BCD”);
cout <<s1;
}
output:
abcdefg

after replace
aBCDefg
String attributes:
The various attributes of the string are size, length,capacity etc.
Example:1
#include<iostream.h>
#include<string.h>
void main( )
{string s1;
cout <<”\n empty :”<<(s1.empty ( )?: “true “: “false “);
cout <<”size= ” <<s1.size( );
cout <<”length =”<<s1.length( );
cout <<”capacity=”<<s1.capacity( );
cout <<”maximum size=”<<s1.max_size( );

s1=”hai “;
cout <<”\n empty :”<<(s1.empty ( )?: “true “: “false “);
cout <<”size =”<<s1.size();
cout<<”length = “<<s1.length( );
cout <<”capacity=”<<s1.capacity( );

s1=”abcdefghijklmnopqrstuvwxyz howareyou “
cout <<”capacity=”<<s1.capacity( );

}
Output:
true
size =0
length =0
capacity =0
maximum size = 4294967293

false
size = 3
length = 3
capacity =31
capacity =66
In the above program if nothing is assigned to the string the capacity value will be
displayed as 0 . In case number of characters less than 32 then 31 will be displayed as
the capacity value. In this program the string is assigned with 35 characters . So that the
capacity( ) returns 31+35 =66.

Miscellaneous functions:
1. assign( ) - This function is to assign a string wholly/ partly to other string object.
syntax:
s2. assign( s1) // the content of string s1 is assigned to s2.
s2.assign (s1,0,5)// element from 0 to 5 are assigned to s2.

2. begin( )- Returns the reference of the first character of the string.


Syntax:
x=s1.begin( ) // x is a character pointer and s1 is a string object
Example:
int main( )
{
string s1”c plus plus”);
char *x;
x= s1.begine ();
cout << *x;
return 0;
}
output:
c

10. MODELS AND PROBLEMS TO BE WORKED OUT IN THE CLASS


Unit Models/Problems
I  Write a program to display sum of odd numbers between 1 to
150.
 Write a program to calculate absolute value of long and float
number

II  Write a program to count number of vowels present in the


entered string

III  Illustrate a program to overload member function in base and


derived class

IV  Illustrate a Program to find the determinant of a 2 X 2 matrix


using pointers
V  Illustrate a program to concatenate two string and find the
lenth of the resultant string.

11. MODELS AND PROBLEMS TO BE WORKED OUT IN THE TUTORIALS

Unit Models/Problems
I  Write a program to calculate the factorial of a given number

II  Write a program to display string in reverse using recursion

III  Apply the concept of friend function and create a program

IV  Illustrate program to create dynamic objec

V  Program to evaluate array index out of bounds exception and


arithmetic exception

12. POSSIBLE QUESTIONS FOR TESTING THE KNOWLEDGE AND


UNDERSTANDING

Unit –I
1. List out any 6 OOPs concepts

1. Objects:
Objects are basic run-time entities in an object-oriented system. They may
represent a place, a person, a bank account or any item that the program must handle.
Programming problem is analyzed in terms of objects and the nature of
communication between them.

When a program is executed, the objects interact by sending messages to one


another. For example, if “customer” and “account” are two objects in a program, then
the customer object may send a message to the account object requesting the bank
balance.
2. Classes:
A class is a collection of objects of similar type. For example, mango, apple and
orange are members of the class fruit. The entire set of data and code of an object
can made a user-defined data type with the help of a class. Once a class is defined, we
can create any number of objects belonging to that class.

3. Data abstraction:
Abstraction refers to the act of representing essential features without including
the background details or explanations. Classes use the concept of abstraction and are
defined as a list of abstract attributes such as size, weight and cost, and functions to
operate these attributes.

4. Data encapsulation:
The wrapping up of data and functions into a single unit (called class) is known as
encapsulation. Data encapsulation is the most striking feature of a class. The data is
not accessible to the outside world and only those functions which are wrapped in the
class can access it.

5. Inheritance:
Inheritance is the process by which one class acquires the properties of objects of
another class. It supports the concept of hierarchical classification. 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.

6. Polymorphism:
Polymorphism means the ability to take more than one form. For example, an
operation may exhibit different behavior in different instances. The behavior depends
upon the types of data used in the operation. For example, consider the operation of
addition. For two numbers, the operation will generate a sum. If the operands are of
strings the result will be the concatenated string.

2. Justify i/o streams in c++

Streams in C++

Stream is a flow of data in bytes in sequence. If data is received from input devices in
sequence then it is called as source stream and when the data is passed to output devices then it is
called destination stream. Data in source stream can be used as input data by the program. So,
the source stream is also called as input stream. The stream is an intermediator between I/O
devices and the user.

Predefined streams

Pre-defined streams are also called as standard I/O objects. These streams are
automatically activated when program execution starts. Some of the pre-defined streams are

 Cin – Standard input, usually keyboards, corresponding to stdin in C.


 Cout – Standard output, usually screen, corresponding to stdout in C.
 Clog – A fully buffered version of cerr. It controls error messages that are passed
from buffer to the standard error device.
 Cerr – Standard error output, usually screen, corresponding to stderr in C.

Stream classes

All C++ stream classes are declared in the header file iostream.h. The file iostream.h
must be included in the program if we are using functions of these classes. The class istream and
ostream are derived classes of base class ios. The iostream contains formatting of both istream
and ostream classes.

The C++ I/O system contains a hierarchy of classes that are used to define various
streams to deal with both the console and disk files. These classes are called stream classes. The
following figure shows the hierarchy of the stream classes used for input and ouptput operations
with the console unit. These classess are declared in the header file iostream.h. This file should
be included in all the programs that communicate with the console unit.

ios is the base class for istream and ostream which are, in turn, base classes for iostream.
The class ios is declared as virtual base class so that only one copy of its members are inherited
by the iostream. The class ios provides the basic support for formatted and unformatted input
while the class ostream provides the facilities for formatted output. The class iostream provides
the facilities for handling both input and ouput streams.

Class : ios


Contains the basic facilities that are used by all the input and output
classes
 Declares constants and functions that are necessary for handling formatted
input and output operations
Class: istream

 Inherits the properties of ios.


 Declares input functions such as get(), getline() and read()
 Contains overloaded extreaction operator >>.
Class : ostream

Inherits the properties of ios.

 Declares for the output functions such as put() and write().


 Contains the overloaded insertion operator <<.
Class : iostream

 Inherits the properties of ios, istream, ostream through multiple


inheritance and thus contains all the input and output functions.

3. State get() and put() functions


put() and get() functions

The istream and ostream classes define two member functions get() and put()
respectively to handle single character input/output operations.
Two types of get() functions.
1. get(char *) – Assigns the input character to its argument.
char c;
cin.get(c); //gets a character from the keyboard
2. get((void) – Returns the input character.
char c;
c=cin.get(); //cin.get(c) is replaced
In this case, the value returned by the function get() is assigned to the variable c.

The function put(), a member ostream class is used to output a line of text, character by
character.

For e.g.,
cout<<put(‘x’); // displays the character x
cout.put(ch); // displays the value of the variable ch.
Number can be as an argument to the function put(). For e.g.,
cout.put(68);

4. State functions in c++

Functions play an important role in programming. Dividing a program into function is one of
the major principles of top-down, structured programming. Another advantage is reducing
the size of the programs. As a result, functions remain as the building blocks of C++
programs with some additional features.

The Main function

In ANSI C,
The definition of main( )
Main( )
{
//main program statements
}
The starting point for the execution of a program is main ( ) that does not return any value. In
C++, main() returns a value of type int to the operating system. Therefore, C++ explicity
defines main( ) as
int main( )
{
……
……
return(0);
}
The functions that have a return value should use the return statement for termination.

Parts Of Function
A function has the following parts:
 Function Prototype declaration
 Definition of a function
 Function call
 Actual and formal arguments
 The return statement.

Function Prototype
The prototype describes the function interface to the compiler by giving details such as the
number and type of arguments and the type of return values. When a function is called, the
compiler ensures that proper arguments are passed or the return value is correct. Any
violation in matching the arguments or the return types will be indicated by the compiler at
the time of compilation itself. In C++, function prototyping is essential.Function prototyping
is a declaration statement in the calling program and with the syntax as follows:
type function-name(argument-list);
The argument list contains the types and names of arguments that must be passed to
the function. Each argument variable must be declared independently inside the parentheses.
The variable names in the argument list can be excluded.
For e.g.
float mean(int a, int b)
Function Definition
The block of statements followed by function declarator is called as function declarator.
The declarator and function prorotype declaration should match each other. The function
body is enclosed with curly braces.
Function Call
A function gets activated only when a call to function is invoked. A function must be
called by its name, follwed by argument list enclosed in parenthesis and terminated by semi-
colon.
Actual and Formal aguments
The arguments declared in caller function and given in the function call are called as
actual arguments. The arguments declared in the function declarator is known as formal
arguments.
The return Statement
The return statement is used to return value to the caller function. The return
statement returns only one value at a time. When a return statement is encountered,
compiler transfers the control of the program to caller function

5. Elucidate inline functions


The concepts in using functions in programs is to save memory space, which becomes
appreciable when a function is called many times. Every time a function is called, it takes a
lot of extra time in executing a series of instructions for tasks such as jumping to the
function, saving registers, pushing registers, pushing arguments into the stack and returning
to the calling function. When a function is small, a substantial percentage of execution time
is spent in such overheads.
In C++, solution to above problem is the use of inline functions. An inline function is a
function that is expanded in line when it is invoked. The compiler replaces the function call
with the corresponding function code, Definition of inline functions is
inline function-header
{

function body
}
Example:
inline double cube(double a)
{
return(a*a*a);
}
Inline function is invoked by statement like
c = cube(2.0);
All inline functions must be defined before they are used. The speed benefits of inline
functions are lost as the size of inline function grows. In such cases, the use of normal
function will be more meaningful. As a result, the function are made inline when they are
small enough to be defined in one or two lines.
The keyword inline indicates a request to the compiler and this request is ignored if
the function is too long or complicated. The other situations when inline functions do not
work are
 If the function has a loop, switch or goto statements
 If the function contains static variables
 If the function is recursive
 If the return statement does not exist
Inline function is advantageous in the fact that the program runs faster but it
consumes memory because the function is inserted at each point the function is called.

Unit –II

1. State about static member functions

Like static data members, static member functions can also be defined. A static
member function has the following properties :
 A static function can access only static members declared in the same class
 A static function can be called using the class name as
Class_name :: function_name();
It is also possible to invoke static member functions using objects.
Example:
#include<iostream.h>
class test
{
int code;
static int count;
public:
void setcode()
{
code = ++count;
}
void showcode()
{
cout<<”Object number:”<<code;
}
static void showcount()
{
cout<<”count:”<<count;
}
};

int test :: count=0;


void main()
{
test t1, t2;
t1.setcode();
t2.setcode();
test :: showcount();
test t3;
t3.setcode();
test::showcount();
t1.showcode();
t2.showcode();
t3.showcode();
}
Output:
Count : 2
Count : 3
Object number : 1
Object number : 2
Object number : 3
The static function showcount() displays the number of objects created till that
moment. A count of the number of objects created is maintained by static variable
count.

2. Elucidate friend functions


Friend functions
There will be times when you want a function to have access to the private members of
a class without that function actually being a member of that class. For this purpose, C++
supports friend functions. A friend function is not a member of the class but still has access to
its private members.
 A friend function is declared as a regular non member functions. The function’s
prototype is included in the class declaration of the class for which it is a friend
function. The prototype is prefaced by the keyword friend.
 Since friend function is not a member of a class, it is not possible to call a friend
function by using an object name and a class member access operator(a dot or arrow).
Instead, friend functions are called just like regular functions.
 Although a friend function has knowledge of the private elements of the class
for which it is a friend, it can only access them through an object of the class. Normally
a friend function has objects as its arguments.
Example:
#include<iostream.h>
class B;
class A
{
int num1;
public :
void setvalue(int i)
{ num1=i; }
friend void max(A o1, B o2);
};
class B
{
int num2;
public:
void setvalue(int i)
{ num2=i; }
friend void max(A o1, B o2);
};
void max(A o1, B o2)
{
if(o1.num1>o2.num2)
cout<<”Greatest number:”<<o1.num1;
else
cout<<”Greatest number:”<<o2.num2;
}
void main()
{
A o1;
B o2;
o1.setvalue(10);
o2.setvalue(20);
max(o1,o2);
}
The program tries to compare the value in class A and the value in class B and
tries to print the greatest number. It is possible to access the private member of class A
and B within the function max, as it is a friend of both the classes.
The function max() has arguments of type A and B. When the function is
declared as a friend in class A for the first time, the compiler will not acknowledge the
presence of class B unless its name is declared in the beginning as
class B;
This type of declaration is called forward declaration.

3. Justify overloading member functions

Member functions can be overloaded in the same method as other ordinary functions.
Overloading is nothing but one function is defined with multiple definitions with same
function name in the same scope.
Example
#include<iostream.h>
#include<conio.h>
Class num
{
int a,b,c;
float c,d,e;
Public:
int add(int,int);
float add(float,float);
void display();
};
int num::add(int x, int y)
{
int t;
T=x+y;
Return t;
}
float num::add(float x,float y)
{
float t;
T=x+y;
Return t;
}
Void num:: display()
{
cout<<add(2,3);//function call
cout<<add(2.3,1.3);//function call
}
Void main()
{
num n;
n.display();
getch();
}

In the above program the member function add is overloaded.

4. List out the Characteristics of constructors and destructors

Characteristics of constructors and destructors

Constructors:

1. Constructor has the same name as the class name.

2. Constructor is executed when an object is declared.

3.Constructors have neither void nor return value.

4. The main function of constructor is to initialize objects.

5. Though constructors are executed implicitly they can be invoked explicitly.

6. Constructor can have default can be overloaded.

7. The constructor without arguments is called as default constructor.

Destructors:

1. Destructor has the same name as that of the class it belongs to and precede by ~ (tilde)

2. Like constructor, the destructor does not have return type and not even void.

3. Constructor and Destructor cannot be initialized

4. Destructors can be virtual, but constructors cannot.

5. Only one destructor can be defined in the destructor. Destructor does not have any arguments.
6. The destructors neither have default values nor can be overloaded.

7. Programmers cannot access addresses of constructors and destructors.

5. Programs Calculate Prime Number Using Constructor

#include<iostream.h>

#include<conio.h>
class prime
{
int a,k,i;
public:
prime(int x)
{
a=x;
}
void calculate()
{
k=1;
{
for(i=2;i<=a/2;i++)

if(a%i==0)
{
k=0;
break;
}
else
{
k=1;
}
}
}

void show()
{
if(k==1)
cout<< “\n\tA is prime Number. ";
else
cout<<"\n\tA is Not prime.";
}
};

void main()
{
clrscr();
int a;
cout<<"\n\tEnter the Number:";
cin>>a;
prime obj(a);
obj.calculate();
obj.show();
getch();
}

Unit- III
1. State overloading unary, binary operators
Overloading Unary Operators : -

A minus operator , when used as a unary takes just an operand. When applied to an object , it
should change the sign of each of its data members.
Operator function as member function to overload minus operator.

Eg:
Void space :: operator – ( )
{
x = - x;
y = - y;
z = - z;
}
main( )
{
space s;
s.getdata( 10, -20,30);
-s;
s.display ( );
}

Here function operator –( ) takes no argument the function changes the sign of data
members of S. The statement
S2 = - S1 will not work because the function does not return a value.

Operator function as a friend function to overload minus operator.

Friend void operator – ( space &s );


Void operator – ( space &s )
{
s.x = -s.x;
s.y = -s.y;
}
Pass by value does not work because only a copy of the object that activated the call is
passed to operator – ( ). The changes made inside the operator function will not reflect in the
called object.
Overloading Binary Operators : -
To overload the + operator which accepts two operands is as
C= A+B;
For eg;
complex complex :: operator + ( complex c )
{
complex temp;
temp.x = x + c.x;
temp.y = y + c.y;
return(temp);
}

In the above case, function receives a single argument and returns an object, both of type
complex. The invoking statement for the above operator function is
c3 = c1 + c2;
The function is expected to add 2 complex values, but receives only one argument. So the
statement is equivalent to
c3 = c1.operator + (c2);
Therefore, in the operator+() function, the data members of c1 are accessed directly and
the data members of c2(passed as an argument) are accessed using the dot operator.
temp.x = x + c.x;
where c.x refers to the object c2, x refers to the object c1. temp.x is the real part of the result.
The function returns temp which is of object c3.
As a rule, the right hand operand is passed as an argument, whereas the left hand operand is used
to invoke the function.

2. List out the rules for overloading

Rules for Overloading :-


- Overloading can be done only on existing operators. New operators cannot be overloaded.

- The overloaded operator must have at least one user-defined type operand.

- The basic meaning should not be changed.

- Overloaded operators follow the syntax rules of the original operators..

- A few operator can not use friend function, but member function can do the same .

- Binary operators takes one argument in the case of member function and two arguments in the
case of friend function.

- When using binary operators overloaded through a member functon, the left hand operand
must be an object.

- Binary operators such as + , - ,* and / must explicitly return a value.

- There some operators that cannot be overloaded.


3. List any 3 type of inheritance

Multilevel Inheritance
A class derived from another derived class. The class A serves as a base class for the derived class B
which in turn serves as a base class for the derived class C.

Base Class A Grandfather

Intermediate Base B Father


Class

Derived Class C Child

Multilevel Inheritance

A derived class with multilevel inheritance is declared as follows:


class A
{ };
class B : public A
{ };
class C : public B
{ };
Consider an example, The test results of students are stored in 3 different classes. Class student
stores the rollnumber and name, class test stores the marks obtained in two subjects and class result
contains the total marks obtained in the test. The class result can inherit the details of marks obtained in
the test and roll number of students through multilevel inheritance.
#include<iostream.h>
class student
{
protected :
int roll_number;
char name[20];
public :
void get_number(int a,char nm[20])
{
roll_number=a;
name=nm;
}
void display_number()
{
cout <<roll_number;
cout<<name;
}
};
class test :public student
{
protected :
int mark1,mark2;
public :
void get_marks(int m1,int m2)
{
mark1=m1;
mark2=m2;
}
void display_marks()
{
cout << mark1;
cout<< mark2;
}
};
class result : public test
{
protected :
int total;
public :
void display_total()
{
total = mark1 + mark2;
display_number();
display_marks;
cout << total;
}
};
main()
{
result object;
object.get_number(101,”Anu”);
object.get_marks(90,80);
object.display_total();
}
Multiple Inheritance
A class can inherit the attributes of two or more classes. This type of inheritance is called multiple inheritance.

B-1 B-2 B-3

D
Multiple Inheritance
Syntax of a derived class with multiple base class is as follows:
class D : visibility mode B-1, visibility mode B-2,…..
{
…….
…..
};
where visibility may be public or private. The base class are separated by commas.
For eg.
class M
{
protected :
int m;
public :
void get_m(int a)
{
m=a;
}
};
class N
{
protected :
int n;
public :

void get_n(int b)
{
n=b;
}
};
class P : public M, public N
{
public :
void display()
{
cout<<m*n;
}
};
main()
{
P objp;
objp.get_m(10);
objp.get_n(5);
objp.display();
}

Hierarchical Inheritance
Another interesting application of inheritance is to use it as a support to the hierarchical design of
a program. Many programming problems can be cast into a hierarchy where certain features of one level
are shared by many others below that level

Students

Arts Engineering Medical

Mech. Elec Civil

4. Elucidate virtual base class


In a situation where all the types of inheritances such as multilevel and multiple are
involved, the child may have two direct base classes ‘parent1’ and ‘parent2’ which themselves
have a common base class ‘grandparent’. The ‘child’ inherits the traits of ‘grandparent’ via two
separate paths. The ‘grandfather’ is sometimes referred to as indirect base class. As result, child
Grandparent
inherits the properties of the two parent classes and thus it contains duplicate copies of the
parent. In other words the child inherits the traits of the grandparent via two separate paths.

Parent 1 Parent 2

Child
The duplication of inherited members due to these multiple paths can be avoided by
making the common base class as virtual base class while declaring the direct or intermediate
base classes
class A //grandparent
{---------};
class B1 : virtual public A //parent1
{---------};
class B2 : public virtual A //parent2
{---------};
class C : public B1,public B2
{---------}; //only one copy of A is inherited

5. Explain type conversion

Type Conversions:-
Constants and variables of different types are mixed in an expression to which certain
rules are applied as per rules in C. An assignment operation also causes the automatic type
conversion. Compiler does not support automatic type conversion for user-defined data types.

Three types of conversions are possible:


- conversion from built in to class type.

- conversion from class to built in type.

- conversion from one class to another class type.

Unit-IV

1. List out the Rules for virtual functions

Rules for virtual functions

 Virtual members must be members of some class.


 They cannot be static members.
 They are accessed by using object pointers.
 A virtual function can be a friend of another class.
 constructors cannot be declared as a virtual, but destructors can be declared as virtual.
 the virtual function must be defined in public section of the class. It is also possible to
define the virtual function outside the class. The virtual keyword is used In the function
declaration but not in the function declarator.
 it is possible to return a value from virtual function like other functions.
 arithmetic operation cannot be used with base class pointer.
 A virtual function in a base class must be defined though it is not used.
 virtual constructors is not possible but virtual destructors is possible.
 The operator keyword used for operator overloading also supports virtual mechanism.

2. Elucidate virtual functions

An essential requirement of polymorphism is the ability to refer to objects without


any regard to their classes. This necessitates the use of a single pointer variable to
refer to the objects of different classes. So, the pointer to a base class is used to refer
all the derived objects. But, when a base pointer is used and it contains the address of
a derived class, always executes the function in the base class. So the concept of
polymorphism is not used. It is achieved using what is known as ‘virtual’ functions.

When the same function name used in both the base and the derived classes, the
function in base class is declared as virtual using the keyword virtual preceding its
normal declaration. When the function is made virtual, C++ determines which
function to use at run time based on the object pointed to by the base pointer, rather
than the type of the pointer . Thus by making the base pointer point to different
objects different versions of the virtual function can be executed.

Example:

class base
{
int a;
public:
void display()
{
cout<<”base”;
}

virtual void show()


{
cout<<a;
}
};
class derived
{
int b;
public:
void display()
{
cout<<”Derived”;
}
void show()
{
cout<<b;
}
};
void main()
{
base *ptr;
base b;
ptr=&b;
ptr->show(); //invokes base class show()
ptr->display(); //invokes base class display()
derived d;
ptr=&d;
ptr->display(); //invokes base class display()
ptr->show(); //invokes derived class show() because base show() is
virtual
//and also now the pointer ptr has the address of derived obj.
}

3. Explain array of pointers

Polymorphism refers to late binding. Address of different objects can be


stored in an array to invoke function dynamically.

Example:
Class a
{
public :
virtual void show( )
{
cout<<”a\n”;
}};
class b : public a
{
public:
void show() {cout <<”b\n”;}};
class c:public a
{
public :
void show()
{
cout <<”c\n”;
}};
class d : public a
{
public:
void show()
{
cout <<”d\n”;
}};
class e: public a
{
public :
void show ( )
{cout <<”e”;
}};
void main()
{
a a1; b b1; c c1; d d1; e e1;
a * pa[]={&a1,&b1,&c1,&d1,&e1};
for (int j=0; j<5;j++)
a[j]->show();
}

4. Justify pure virtual functions

Function in the base class is declared virtual and it is redefined in the derived
class, but base class virtual function does not perform any task. So they are called
as ‘do-nothing’ functions. It is defined as

virtual void display()=0;

These functions are also known as pure virtual functions. It is a function


declared in the base class with no definitions. A class with pure virtual function
cannot be used to create objects Such classes are called as abstract base classes.

Example:

Class first

protected:

int b;

public:

irst(){b=10;}

virtual void display () =0;//puer function

};

class second: public first

{
int d;

public :

second( )

{d=20;}

void display()

cout <<”\n b= “<<b<<”d = “<<d;}};

void main()

first *p;

second s;

p= &s;

p->display();

5. State abstract classes

Abstract classes are like skeleton upon which new classes are designed to
assemble well designed class hierarchy. The well tested abstract classes can
be used and the programmer only extends them.

Example:

// The file abstract.h is an example of file containing abstract base class used
for debugging purpose.

Contents of “abstract.h” file

#include <iostream.h>
struct debug
{
virtual void show( )
{
cout <<”\n no function show( ) defined for this class”;
}};
Unit V

1. Elucidate file stream classes

The I/O system of C++ contains a set of classes that define the file handling

methods. They include ifstream, ofstream and fstream. They are derived from

fstreambase class and from the corresponding iostream.h class. These classes are

designed to manage the disk files and are declared in fstream.h and therefore this file

should be included in any program that uses these files.

The other file stream classes available are:

Class Contents

filebuf Its purpose is to set the file buffers to read and write.It also

contains close() and open() as members.

fstreambase Provides operations common to file streams. Serves as a base for

fstream, ifstream and ofstream classes. Contain open() and

close() functions.

ifstream Provides for input operations. It contains open() with default input

mode. Inherits the functions get(),getline(), read(),seekg()

and tellg() from istream.

ofstream Provides for output operations. It contains open() as the default

output mode. It inherits put(),seekp(),tellp() and write()

functions from ostream.

fstream Provides support for simultaneous input and output operations.

Contains open() as the default input mode. It inherits all the

functions from istream and ostream classes through

iostream.
2. Elucidate file pointer and their manipulations

Each file has two associated two pointers known as file pointers .

1. Input(get) pointer – Used for reading the contents of a given file location

2. Output(put) pointer - Used for writing to a given file location

Default actions

When a file is opened in read-only mode the input pointer is automatically set at the
beginning of the file. When opened in write-only mode then the existing contents of the file are
deleted and the output pointer is set at the beginning. If it is opened in append mode then the
pointer is at the end of the file so that new data can be added thereafter.

Functions for manipulation of file pointers

File stream classes support the movement of pointers using the following functions:

seekg() – Moves the input pointer to a specified location.

For eg.

infile.seekg(10)

This statement makes the pointer to point to the 11 thposition because the numbering starts from
zero.

seekp() - Moves the output pointer to a specified location

tellg() - Gives the current posiition of the get pointer

tellp() - Gives the current position of the put pointer.

For eg.

ofstream fileout;

fileout.open(“hello”,ios::app);

int p= fileout.tellp();

In the above case, the output pointer is moved to the end of the file “hello” and p represents the
number of bytes in the file.
Specifying the offset

seekp() and seekg() have two arguments each, such as

seekg ( offset, refposition );

seekp ( offset, refposition );

Here offset represents the number of bytes the file pointer is to be moved from the
location specified by the parameter refposition. Refposition can be one of te following 3
constants,

4. ios::beg – start of the file


5. ios::cur – current position of the pointer
6. ios::end – end of the file

The seekg() function moves the associated file’s get pointer while seekp function moves
the associated file ‘s put pointer. fout is an ofstream object.

Seek call Action

fout.seekg(0,ios::beg); Go to the start

fout.seekg(0,ios::cur); Stay at the current position

fout.seekg(0,ios::end); Go to the end of the file

fout.seekg(m,ios::beg); Move to (m+1)th byte in the file

fout.seekg(m,ios::cur); Go forward by m bytes from the

current position

fout.seekg(-m,ios::cur); Go backward by m bytes from the

current position

fout.seekg(-m,ios::end); Go backward by m bytes from the

end

3. create a program using string attribute

#include<iostream.h>
#include<string.h>

void main( )

{string s1;

cout <<”\n empty :”<<(s1.empty ( )?: “true “: “false “);

cout <<”size= ” <<s1.size( );

cout <<”length =”<<s1.length( );

cout <<”capacity=”<<s1.capacity( );

cout <<”maximum size=”<<s1.max_size( );

s1=”hai “;

cout <<”\n empty :”<<(s1.empty ( )?: “true “: “false “);

cout <<”size =”<<s1.size();

cout<<”length = “<<s1.length( );

cout <<”capacity=”<<s1.capacity( );

s1=”abcdefghijklmnopqrstuvwxyz howareyou “

cout <<”capacity=”<<s1.capacity( );

Output:

true

size =0

length =0

capacity =0

maximum size = 4294967293

false

size = 3

length = 3
capacity =31

capacity =66

In the above program if nothing is assigned to the string the capacity value will be
displayed as 0 . In case number of characters less than 32 then 31 will be
displayed as the capacity value. In this program the string is assigned with 35
characters . So that the capacity( ) returns 31+35 =66.

4. How to declare and initialize string objects?

//program to declare string objects. Perform assignment and concatenation


operations with the string objects//

#include<iostream.h>

#include <string.h>

void main()

string text;

string text1(“CPP”);

stringt text1(“oop”);

cout<<text1<<text2;

text=text1;

cout <<text;

text=text1+ “ “+text2;

cout <<text;

In the above program three objects text,text1,text2 of type string are declared. The
text1 and text2 are initialized with “CPP” and “oop”. The object text is initialized
with the contents of beject text1 using operator “ =”.So that the value of text will be
CPP. The again it is reassigned with the joined value of object text1and text2. and
display the output as

CPP oop

5. List out the miscellaneous functions

Miscellaneous functions:

3. assign( ) - This function is to assign a string wholly/ partly to other string object.
syntax:

s2. assign( s1) // the content of string s1 is assigned to s2.

s2.assign (s1,0,5)// element from 0 to 5 are assigned to s2.

4. begin( )- Returns the reference of the first character of the string.


Syntax:

x=s1.begin( ) // x is a character pointer and s1 is a string object

Example:

int main( )

string s1( ”c plus plus”);

char *x;

x= s1.begine ();

cout << *x;

return 0;

13. LIST OF APPLICATIONS /CASE STUDIES AND THE CONCEPTS TO BE USED

 Function overloading
 Virtual functions
 Array of Pointers
 How to access the member functions in a class? List out the ways and develop own
program

14. ASSIGNMENT I
S.NO TOPICS ASSIGNED ISSUED
DATE DATE
1 Decision making statements ,
Looping statements in c++
2 i) Use the concept of inheritance
and create a program for student
database
15. LIST OF SKILLS IN WHICH THE STUDENTS ARE TO BE TRAINED THROUGH
THE COURSE

 Creating Objects to the Class


 Accessing member functions in different ways
 Various type of functions
 Inheritance
 Overloading functions
 File concepts
 Templates
 Exception handling
 Strings
16. RELEVANT CONCEPTS AND TOPICS THE STUDENTS TO BE INTRODUCED
(RELEVANT TO THE SKILLS).
 Function Overloading
 Virtual functions
 Error Handling
 Arrays
 String Functions
 File operations

17. TUTORIAL QUESTIONS / PROBLEMS FOR THE TUTORIAL SESSION

1. Implement the concept of function overloading


2. Use the concept of manipulator and create a program
3. Write a program to demonstrate call by value
4. Create a program to overload member function f a class
5. Illustrate a program to create constructor with arguments and pass the arguments to the
constructor
6. Create a program to overload binary operator
7. Implement the concept of multiple inheritance
8. Use the concept of this pointer and create a program
9. Create a program to read and display contents of file
10. Illustrate a program to catch multiple exceptions

24. ASSIGNMENT II

S.NO TOPICS ASSIGNED ISSUED


DATE DATE
1 Illustrate the concept of virtual
functions
2 Illustrate file concepts and
miscellaneous functions

36. SCOPE OF THE COURSE RELEVANT TO SPECIFIC SKILL/JOB ETC.,


 Developer
 Programmer
 Compiler developer
 Algorithm engineer
 Game developer

37. KNOWLEDGE IMPARTED TO THE STUDENT AT THE END OF THE COURSE

 Manipulate various C++ datatypes, such as arrays, strings, and pointers


 Isolate and fix common errors in C++ programs
 Use memory appropriately, including proper allocation/deallocation procedures
 Apply object-oriented approaches to software problems in C++
 Be able to implement, test, debug, and document programs in C and C++
 Program with pointers and arrays, perform pointer arithmetic, and use the preprocessor
 Be able to write programs that perform explicit memory management
 Understand how to write and use functions, how the stack is used to implement function
calls, and parameter passing options

38.SKILLS DEVELOPED BY THE STUDENT AT THE END OF THE COURSE

After completion of this course, the students would be able to


 Creating class and objects in C++
 Write clear, elementary C++ programs
 Implementing inheritance, polymorphism and object relationship in C++
 Constructors and destructors programs
 Data manipulation through file in C++
 Friend functions ,Overloading of function and operator
 Understand algorithmic thinking and apply it to programming.
 Understand problem-solving techniques.
 Able to write user-defined function definitions.
 Pass arrays to functions and pointers.
 Various Exception handling

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy