Advanced C++ Course File
Advanced C++ Course File
CONTENTS
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.,
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 _ _
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
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
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
15 17MCC0026 SAVITHA. A
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
IV Pointers, Arrays
V File concepts, Exception Handling
Unit – I:
Oops concepts
Various types of function
Data type
Unit – II:
Unit – III:
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.
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.
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.
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.
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.
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
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.
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
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
Class : iostream
Ios
ostream
istream Streambuf
iostream
Ostream_withstream
Istream_withassignn Iostream_withassign
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.
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.
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;
45
or
cout<<item1<<item2<<item3<<….
The istream and ostream classes define two member functions get() and put()
respectively to handle single character input/output operations.
char c;
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);
C++ supports a number of features for formatting the output such as:
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).
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”;
* * * * * * 5 2 5 0
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”;
T A B L E 1 * * * * * * * *
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
Flags Meanings
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:
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
For e.g.
//This is an example of
The C comment symbols /*, */ are still valid and more suitable for multilane comments.
For e.g.
/*This is an example of
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.
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.
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.
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++:
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)
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.
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);
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:
The if statement
1) Simple statement
if (conditional exp)
action1;
action2;
action3;
2) if..else statement.
if (conditional expression)
action1;
else
action2;
action3;
casel:
{
action 1;
case2:
{
action2:
case3:
actions:
}
default:
{
action4;
}
}
action 5;
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;
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++
Operator Associativity
:: 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
= *= /= %= += -=
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.
Main( )
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
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.
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.
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 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
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.
void main()
int s=4;
funA(s);
funB(s);
funC(s);
void funA(int i)
i++;
k++;
++*j;
}
OUTPUT
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
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
A program to find the area of the rectangle, triangle, and sphere using function overloading.
#include<iostream.h>
#define pi 3.14285
void main()
int area1;
int area2;
double area3;
area1=calcarea(10,20);
area2=calcarea(4.5,2.1);
area3=calcarea(3.12145);
return (length*breadth);
return ((0.5)*base*height);
return ((4/3)*pi*radius*radius);
EXPECTED QUESTIONS
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 function definitions – tells how the class functions are implemented
{ private:
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
The body of the class is enclosed within the curly brackets and terminated by a semicolon.
private
public
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:
float cost;
void putdata();
};
Declaring objects Object is an instance of a class. Each object of the class has its own copy
of
Item x;
Objects can be created by placing their names immediately after the class declaration
Example:
Class item
float cost;
public:
void putdata();
} x, y, z;
The object can access the public member variables and functions of a class by using operator
Example.
*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
The private keyword is used to prevent direct access to member variables or function by the
object.
a.show();
c->show();
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 :
{ Body of function//}The membership label class-name:: tells the compiler that the
function are
Different classes can have the same function name. The membership label identifies
the scope.1
A member function can call another member function directly, without using the dot
operator.
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
Example:
# include< iostream.h>
class item
public:
float cost;
};
cost=b;
Void main()
item x;
x.putdata();
Output:
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
{ int a; int b; int add(); int subtract(); int multiply(); int divide();public : void
{ a = x; b = y;}
{ return (a+b);}
{ return(a-b);}
{ return(a*b);}
{ return(a/b);}
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
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 function can access only static members declared in the same class
Class_name :: function_name();
Example:
#include<iostream.h>
class test
int code;
static int count;
public:
void setcode()
void showcode()
};
void main()
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
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<<”Object number:”<<code;
cout<<”count:”<<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:
{ int eno; char name[30]; float basicpay; float hra; float cca; float
ma; float it; float pf;public : void getdata(); float grosspay(); float deduction();
e[i].display();}
10 employee objects are created as an object array e[10]. Each object is referred by
specifying the
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
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
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
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
#include<iostream.h>class B;
class A
{ num1=i; }
{ num2=i; }
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
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
Example
#include<iostream.h>
#include<conio.h>
Class num
int a,b,c;
float c,d,e;
Public:
int add(int,int);
};
int t;
T=x+y;
Return t;
float t;
T=x+y;
Return t;
cout<<add(2,3);//function call
cout<<add(2.3,1.3);//function call
}
Void main()
num n;
n.display();
getch();
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-
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 ( -> ) is acceptable. The unnamed
bit fields
1. Bits fields should have intearal type. A pointer array type is now allowed .
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
A constructor function has the same name as the class of which it is a part and has no return
type.
Example:
#include<iostream.h>
class myclass
{ int a;
public :
myclass();
void show();
};
myclass ::myclass()
{
cout<<”In_constructor”;
a = 15;
cout<<”value of a:”<<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
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
#include<iostream.h>
class samp
int a;
public:
samp()
cout<<"object created";
a=10;
show()
cout<<a;
~samp()
cout<<"Object destroyed";
};
void main()
samp s;
s.show();
}
Output:
Object created
10
Object destroyed
Constructors:
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.
5. Only one destructor can be defined in the destructor. Destructor does not have any
arguments.
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
Example
Num x;
x.::~num();
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<<”Constructor called”;
n++;
cout<<n;
~num()
Cout<<”Destructor called”;
-- n;
Cout<<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?
9 write a function to find largest among three given numbers using call by
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
function members
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
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.
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
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
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
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.
A minus operator , when used as a unary takes just an operand. When applied to an object , it
should
x = - x;
y = - y;
z = - z;
main( )
space s;
-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.
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.
C=A+B;
For eg;
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
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
As a rule, the right hand operand is passed as an argument, whereas the left hand operand is
used to
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 statement, C3 = c1 + c2 is interpreted as
Friends are used in cases where two different types of operands for a binary operator such as
an
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
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 = 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
char *p;
int len;
public:
-- -- -- -- -- -
-- -- -- -- -- -
if (m <= n )
return (1);
return(0);
string temp ;
strcpy (temp.p,s.p);
return (temp);
- 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.
- 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
- When using binary operators overloaded through a member functon, the left hand operand
must be an object.
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.
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.
strcpy (p,a);
This constructor can be used for conversion from char * type to string type.
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
The constructor does not support the conversion from class to basic type. This conversion is
made
operator typename( )
-- -- -- --
-- -- -- --
function statement
double sum = 0;
{
sum = sum + v [ i] * v [i];
}
return sqrt(sum);
}
This function converts a vector to double scalar magnitude. The costing operator function
This being a member function, it is invoked using an object and the values used for
conversion
return(p);
Obj X = Obj Y
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.
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
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
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
#include<iostream.h>
#include<conio.h>
Class plusplus
private:
int num;
public:
operator typename ()
plusolus()
num = 0;
Int getnum()
return num;
Plusplus tmp;
num = num + 1;
temp.num= num;
return tmp;
Void main()
clrscr();
plusplus p1,p2;
cout<<”\n p1 = “<<p1.getnum();
cout<<”\n p2 = “<<p2.getnum();
p1=p2++;
cout<<endl<<”p1 = ”<<p1.getnum();
cout<<endl<<”p12= ”<<p2.getnum();
p1++;
cout<<endl<<”p1 = ”<<p1.getnum();
cout<<endl<<”p12= ”<<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
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.
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
statement1;
statement2;
Example program
#include<iostream.h>
#include<conio.h>
class complex
float real,img;
public:
complez()
real=img=0;
complex(float r, float i)
real =r;
img=i;
c.real= -c.real;
c.img=-c.img;
return c;
void display()
Void main()
clrscr();
complex c1(1.5,2.5);
c1.display();
c2= -c1;
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.
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.
The derived class is defined by specifying its relationship along with the base class.
Multiple inheritance :
Multilevel inheritance:
Hierarchical inheritance:
For Eg.,
-- --
};
-- -- //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
public:
int b;
void getdata();
};
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.
class base
public:
int b;
void getdata();
};
int c;
public:
void display();
};
main()
derived objd;
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
class base
public:
int b;
void getdata();
};
int c;
public:
void display()
getdata();
};
main()
{
derived objd;
objd.display();
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
Multilevel Inheritance
A class derived from another derived class. The class A serves as a base class for the derived
class B
Class
Multilevel Inheritance
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
#include<iostream.h>
class student
protected :
int roll_number;
char name[20];
public :
roll_number=a;
name=nm;
void display_number()
cout <<roll_number;
cout<<name;
};
protected :
int mark1,mark2;
public :
mark1=m1;
mark2=m2;
void display_marks()
cout<< mark2;
}
};
protected :
int total;
public :
void display_total()
display_number();
display_marks;
};
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.
Multiple Inheritance
Syntax of a derived class with multiple base class is as follows:
…….
…..
};
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
n=b;
};
public :
void display()
cout<<m*n;
};
main()
P objp;
objp.get_m(10);
objp.get_n(5);
objp.display();
Hierarchical Inheritance
a program. Many programming problems can be cast into a hierarchy where certain features
of one level
Students
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.
student
test sports
result
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
12
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
{-- -- -- -- -};
{-- -- -- -- -};
{-- -- -- -- -};
Abstract Classes:
An abstract class is one which is not used to create objects. It is designed to act as a base
class
SUGGESTED QUESTIONS
UNIT IV
4.1.1. POINTERS, VIRTUAL FUNCTIONS AND POLYMORPHISM:
defined and shared by various objects to perform the operation. The concept of
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
Example :
class first
public:
void display ()
};
int d;
{ 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
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
Example :
public:
};
public :
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
int d;
int k ;
-- -- -- -- -- -- -- //derived class member function
Polymorphism
Compile time
Polymorphism Runtime
Polymorphism
Function
Overloading
Operator
Overloading
Virtual
functions
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
Example :
// program to access members of base and derived classes using pointer objects
of both classes
# include <iostream.h>
#include<conio.h>
class w
protected :
int x;
public:
w(int k) {x=k;}
void show( )
};
};
class y : public w
protected:
int z;
public :
z=k;
void show ( )
cout<<”\n x=”<<x;
};
class p :public y
{
public :
int q;
};
void main()
clrscr();
w *b;
delete b;
b =new y(3,2);
b- >show( );
delete b;
y r(3,4);
y *d=&r;
d->show( );}
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
of class y. the statement y *d = &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.
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
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
Example:
class base
int a;
public:
void display()
}
virtual void show()
cout<<a;
cout<<”base”;
};
class derived
public:
int b;
void display()
cout<<”Derived”;
void show()
cout<<b;
};
void main()
base *ptr;
base b;
ptr=&b;
ptr=&d;
//and also now the pointer ptr has the address of derived obj.
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
The operator keyword used for operator overloading also supports virtual
mechanism.
Example:
Class a
public :
cout<<”a\n”;
class b : public a
public:
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 * pa[]={&a1,&b1,&c1,&d1,&e1};
pa[j]->show();
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
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
Example:
Class first
protected:
public:
first(){b=10;}
public :
second( )
{d=20;}
void display()
void main()
first *p;
second s;
p= &s;
p->display();
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
Example:
// The file abstract.h is an example of file containing abstract base class used for
debugging purpose.
#include <iostream.h>
struct debug
#include “abstract.h”
#include <constream.h>
int a;
public :
x(int j=0) {
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
3. The derived class should not have pure virtual functions. objects of derived
1. Binding means link between a function call and the real function that is
executed when function is called.
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
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:
};
clas b : public a
{
public :
};
void main()
{}
a *a1,*a2;
a a3;
b b1;
a1=&a3;
a1->joy( );
a2 ->joy( );}
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;
x=y;
Example:
class b
int k;
public :
b( int l) {k=l;}
};
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.
}
};
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.
-------------------------------------------------------------------------------------------------------------------
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.
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.
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:
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”);
Program1:
ofstream outfile(“results”); //open for output only
-------
outfile.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
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.
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.
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
The file mode parameter can take one or more of such constants defined in the class ios.:
Parameter Meaning
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.
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.
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.
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.
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();
}
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
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);
}
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;
}
int main()
{
show(‘A’);
show(7);
show(7.5);
return 0;
}
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.
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)
catch( double d)
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.
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.
Unit Models/Problems
I Write a program to calculate the factorial of a given number
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.
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.
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
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
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);
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.
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
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
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;
}
};
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();
}
Constructors:
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.
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.
#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.
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.
- The overloaded operator must have at least one user-defined type operand.
- 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.
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.
Multilevel Inheritance
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
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
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.
Unit-IV
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”;
}
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();
}
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
Example:
Class first
protected:
int b;
public:
irst(){b=10;}
};
{
int d;
public :
second( )
{d=20;}
void display()
void main()
first *p;
second s;
p= &s;
p->display();
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.
#include <iostream.h>
struct debug
{
virtual void show( )
{
cout <<”\n no function show( ) defined for this class”;
}};
Unit V
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
Class Contents
filebuf Its purpose is to set the file buffers to read and write.It also
close() functions.
ifstream Provides for input operations. It contains open() with default input
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
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.
File stream classes support the movement of pointers using the following functions:
For eg.
infile.seekg(10)
This statement makes the pointer to point to the 11 thposition because the numbering starts from
zero.
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
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,
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.
current position
current position
end
#include<iostream.h>
#include<string.h>
void main( )
{string s1;
cout <<”capacity=”<<s1.capacity( );
s1=”hai “;
cout<<”length = “<<s1.length( );
cout <<”capacity=”<<s1.capacity( );
s1=”abcdefghijklmnopqrstuvwxyz howareyou “
cout <<”capacity=”<<s1.capacity( );
Output:
true
size =0
length =0
capacity =0
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.
#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
Miscellaneous functions:
3. assign( ) - This function is to assign a string wholly/ partly to other string object.
syntax:
Example:
int main( )
char *x;
x= s1.begine ();
return 0;
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
24. ASSIGNMENT II