BSC Mpcs 2nd Sem CPP Notes
BSC Mpcs 2nd Sem CPP Notes
st nd
BSC (MPCs) 1 Year 2 Semester
Programming in C++
Exam Hours: 2Hours / 3Hours Marks: 80U+20I+50P
Unit – I
Introduction to C++: Applications, Example Programs, Tokens, Data Types, Operators,
Expressions, Control Structures, Arrays, Strings, Pointers, Searching and Sorting Arrays.
Functions: Introduction, Prototype, Passing Data by Value, Reference Variables, Using
Reference Variables as Parameters, Inline Functions, Default Arguments, Overloading Functions,
Passing Arrays to Functions.
Object Oriented Programming: Procedural and Object-Oriented Programming, Terminology,
Benefits, OOP Languages, and OOP Applications.
Unit – II
Classes: Introduction, Defining an Instance of a Class, Why Have Private Members? Separating
Class Specification from Implementation, Inline Member Functions, Constructors, Passing
Arguments to Constructors, Destructors, Overloading Constructors, Private Member Functions,
Arrays of Objects, Instance and Static Members, Friends of Classes, Member-wise Assignment,
Copy Constructors, Operator Overloading, Object Conversion, Aggregation.
Unit – III
Inheritance: Introduction, Protected Members and Class Access, Base Class Access
Specification, Constructors and Destructors in Base and Derived Classes, Redefining Base Class
Functions, Class Hierarchies, Polymorphism and Virtual Member Functions, Abstract Base
Classes and Pure Virtual Functions, Multiple Inheritance.
C++ Streams: Stream Classes, Unformatted I/O Operations, Formatted I/O Operations.
Unit – IV
Exceptions: Introduction, Throwing an Exception, Handling an Exception, Object-Oriented
Exception Handling with Classes, Multiple Exceptions, Extracting Data from the Exception
Class, Re-throwing an Exception, Handling the bad_alloc Exception.
Templates: Function Templates–Introduction, Function Templates with Multiple Type,
Overloading with Function Templates, Class Templates – Introduction, Defining Objects of the
Class Template, Class Templates and Inheritance, Introduction to the STL.
Page 1 of 96
Unit – 1
Expressions, Control Structures, Arrays, Strings, Pointers, Searching and Sorting Arrays.
Page 2 of 96
C++ Introduction
Background History:
1. C++ Development started in 1979.
2. During the creation of Ph.D. thesis, Bjarne Stroustrup worked with language called
Simula.
3. Simula is basically useful for the simulation work.
4. Simula was first language to support object-oriented programming paradigm
5. Bjarne Stroustrup identified that this OOP features can be included in the software
development.
6. After that Bjarne Stroustrup started working on the C language and added more extra
OOP features to the classic C.
7. He added features in such a fashion that the basic flavour of C remains unaffected.
8. C++ includes some add-on features such as classes, basic inheritance, in-lining, default
function arguments, and strong type checking
Basic History of C++
1. During 1970 Dennis Ritchie created C Programming language.
2. In the early 1980‟s, also at Bell Laboratories, another programming language was created
which was based upon the C language.
3. C++ is also called as C with classes
4. Stroustrup states that the purpose of C++ is to make writing good programs easier and
more pleasant for the individual programmer.
5. C++ programming language is extension to C Language.
6. In C we have already used increment operator (++). Therefore we called C++ as
“Incremented C” means Extension to C.
Page 3 of 96
Example program:
#include<iostream.h>
#include<conio.h>
#define PI 3.14;
float r;
class circle
{
Public:
float area;
void read( )
{
Cout<<”enter radius of the circle”;
Cin>>r;
}
Void display( )
{
Area=PI*r*r;
Cout<<”area of the circle is”<<area;
}
};
Void main( )
{
Clrscr( );
Circle C1;
C1.read( );
C1.display( );
getech();
}
C++ Tokens
A token is the smallest element of a program that is meaningful to the compiler. Tokens can be
classified as follows:
1. Keywords
2. Identifiers
3. Constants
4. Strings
5. Special Symbols
6. Operators
1. Keyword: Keywords are pre-defined or reserved words in a programming language. Each
keyword is meant to perform a specific function in a program. Since keywords are referred
names for a compiler, they can‟t be used as variable names. C language supports 32 keywords
which are given below:
auto double int struct
break else long switch
case enum register typedef
char extern return union
Page 5 of 96
4. Strings: Strings are nothing but an array of characters ended with a null character („\0‟).This
null character indicates the end of the string. Strings are always enclosed in double quotes.
Whereas, a character is enclosed in single quotes in C and C++.
Declarations for String:
char string[20] = {„g‟, ‟e‟, „e‟, „k‟, „s‟, „f‟, „o‟, „r‟, „g‟, ‟e‟, „e‟, „k‟, „s‟, „\0‟};
char string[20] = “geeksforgeeks”;
char string [] = “geeksforgeeks”;
5. Special Symbols: The following special symbols are used in C having some special
meaning and thus, cannot be used for some other purpose.[] () {}, ; * = #
Brackets[]: Opening and closing brackets are used as array element reference. These
indicate single and multidimensional subscripts.
Parentheses(): These special symbols are used to indicate function calls and function
parameters.
Braces{}: These opening and ending curly braces marks the start and end of a block of
code containing more than one executable statement.
comma (, ): It is used to separate more than one statements like for separating parameters
in function calls.
semi colon : It is an operator that essentially invokes something called an initialization
list.
asterick (*): It is used to create pointer variable.
assignment operator: It is used to assign values.
Pre-processor(#): The preprocessor is a macro processor that is used automatically by
the compiler to transform your program before actual compilation.
6. Operators: Operators are symbols that triggers an action when applied to C variables and
other objects. The data items on which operators act upon are called operands.
Depending on the number of operands that an operator can act upon, operators can be classified
as follows:
Unary Operators: Those operators that require only single operand to act upon are
known as unary operators.For Example increment and decrement operators
Binary Operators: Those operators that require two operands to act upon are called
binary operators. Binary operators are classified into :
1. Arithmetic operators
Page 7 of 96
2. Relational Operators
3. Logical Operators
4. Assignment Operators
5. Conditional Operators
6. Bitwise Operators
Ternary Operators: These operators requires three operands to act upon. For Example
Conditional operator(?:).
It consists have several types. i.e., integer, Character, Float and Boolean data type.
1. Integer Data type: This data type is used to store the whole numbers. The integers do not
contain the decimal points. They take the binary form for storage. The size of the integer can be
either 16 or 32 bits and the range of integer value is -32767 to +32767. Integers are divided in to
several types and ranges given below.
Page 8 of 96
2. Character Data types: This data type indicates that the value stored in the associated
variable is a character. Each character has an equivalent ASCII value (example „A‟ has an ASCII
value of 65). It data type contain only single character, but not allow numeric values. The size
and ranges of values for character data types given below.
3. Floating Data Type: Floating-point Data types are used to store real number (i.e.,
Decimal point numbers). The keyword “float” is used to declare a variable holding floating-point
numbers. It data types consists of only decimal numbers and also having whole numbers. But not
allowing characters. It data type also dividing several types and sizes and ranges given below.
4. Boolean Data Type: It data types consists of only either True or False vales.
User-defined data types:
We have three types of user-defined data types in C++
1. Type definition
2. Enumerated Data type
1. Typedef Declarations
We can create a new name for an existing type using typedef. Following is the simple syntax to
define a new type using typedef −
Page 9 of 96
2. Enumerated Types
An enumerated type declares an optional type name and a set of zero or more identifiers
that can be used as values of the type. Each enumerator is a constant whose type is the
enumeration.
Creating an enumeration requires the use of the keyword enum. The general form of an
enumeration type is −
enum enum-name { list of names } var-list;
OPERATORS in C++
An operator is a symbol that tells the compiler to perform specific mathematical or logical
manipulations. C++ is rich in built-in operators and provides the following types of operators
listed below
1. Assignment Operator
2. Relational Operators
Page 10 of 96
3. Logical Operators
4. Bit-wise Operators
5. Unary Operators
6. Ternary Operator conditional operators
7. Assignment Operators
8. Special Operator
1. Arithmetic Operators
Arithmetic operators are used for performing basic mathematical operations on operands. There
are following arithmetic operators supported by C++ language −Assume variable A holds 10 and
variable B holds 20, then
Example:
#include<iostream.h>
#include<conio.h>
Void main( )
{
int a,b,sum,sub,mul,div,rem;
clrscr( );
cout<<”enter a,b values”;
cin>>a>>b;
sub=a+b;
cout<<”addition value is”<<sum;
sub=a=b;
cout<<”substraction value is”<<sub;
mul=a*b;
cout<<”Multiplication value is”<<mul;
Page 11 of 96
div=a/b;
cout<<”Division value is”<<div;
rem=a%b;
cout<<”Remainder value is”<<rem;
getch( );
}
OUTPUT:
Enter the a,b values
20 10
Addition value is 30
Subtraction value 10
Multiplication value is 200
Division value is 2
Remainder value is 0
2. Relational Operators
Relational or comparison operators are used to compare two operands. The result of the
evaluation is either true or false.
C++ supports the following Relational Operators:
Assume variable A holds 10 and variable B holds 20, then –
Page 12 of 96
3. Logical Operators
Logical operators are used for evaluating a combination of conditions/constraints to get a
resultant value. The result of the evaluation of a Boolean expression is Boolean which is either
true or false. Assume variable A holds 1 and variable B holds 0, then −
4. Bitwise Operators
Bitwise operators in C++ operate on bits of the operands provided. Bitwise operators are
applied only to integral types like integer, character, etc., and not on data types like float, double,
etc.
Operator Description
Binary XOR Operator copies the bit if it is set in one operand but
^
not both.
Page 13 of 96
Binary Left Shift Operator. The left operands value is moved left
<<
by the number of bits specified by the right operand.
5. Assignment Operators
Assignment operator “=” is used to assigning a value to a variable. The LHS of the
assignment operator is a variable and RHS is the value that is to be assigned to the variable. The
value on the right side must be of the same type as that of the variable on the left-hand side.
The below table gives us a description of these assignment operators.
Operator Description
+= Adds RHS operand to LHS operand and assigns the result in LHS operand.
-= Subtracts RHS operand to LHS operand and assigns the result to LHS operand
*= multiplies RHS operand to LHS operand and assigns the result to LHS operand
/= divides RHS operand to LHS operand and assigns the result to LHS operand
As shown in the above table, If x and y are operands, x+=y is equivalent to x = x+y.
Similarly,
x -=y is equivalent to x = x-y.
x *= y is equivalent to x = x*y.
x /= y is equivalent to x = x/y.
6. Special Operators
So far we explored all the major operators in C++. There are some more additional C++
operators that need our attention.
These operators include:
(i) sizeof operator
sizeof is a unary operator that is used extensively in C and C++. Sizeof returns the size of its
operand. The return value is usually an unsigned integral type denoted by „size_t‟.
(ii) Comma Operator
Comma operator that is represented as a token „,‟ can be used as an operator as well as a
separator.
As an operator, a comma is used when there is more than one expression to be evaluated. Only
the rightmost expression is assigned to LHS.
For Example, consider the following expression.
Page 14 of 96
x = (y=4, y+1);
7. Conditional Operator:
The conditional operator is an operator used in C and C++. The ?: operator returns one of two
values depending on the result of an expression.
Syntax:
The conditional operator is of the form
variable = Expression1 ? Expression2 : Expression3
Here, Expression1 is the condition to be evaluated. If the condition(Expression1) is True
then Expression2 will be executed and the result will be returned. Otherwise, if the
condition(Expression1) is false then Expression3 will be executed and the result will be
returned.
Example:
// C++ program to find largest among two
// numbers using ternary operator
#include <iostream.h>
#include <conio.h>
void main()
{
int n1 = 5, n2 = 10, max;
clrscr( );
max = (n1 > n2) ? n1 : n2;
cout << "Largest number is "<< max;
getch( );
}
Page 15 of 96
2. Decrement
It is used to decrement the value of the variable by 1. The increment can be done in two ways:
1. prefix decrement
In this method, the operator preceeds the operand (e.g., – -a). The value of operand will
be Decremented before it is used.
int a = 1;
int b = --a; // b = 0
2. posfix decrement
In this method, the operator follows the operand (e.g., a- -). The value of operand will be
Decremented after it is used.
int a = 1;
int b = a--; // b = 1
int c = a; // c = 0
Example:
// C++ program to demonstrate working of unary increment
// and decrement operators
#include <iostream.h>
#include <conio.h>
void main()
Page 16 of 96
{
// Post increment
int a = 1;
cout << "a value: " << a << endl;
int b = a++;
cout << "b value after a++ : " << b << endl;
cout << "a value after a++ : " << a << endl;
// Pre increment
a = 1;
cout << "a value:" << a << endl;
b = ++a;
cout << "b value after ++a : " << b << endl;
cout << "a value after ++a : "<< a << endl;
// Post decrement
a = 5;
cout << "a value before decrement: " << a << endl;
b = a--;
cout << "b value after a-- : " << b << endl;
cout << "a value after a-- : " << a << endl;
// Pre decrement
a = 5;
cout << "a value: "<< a<<endl;
b = --a;
cout << "b value after --a : " << b << endl;
cout << "a value after --a : " << a << endl;
getch( );
}
OUTPUT:
a value: 1
b value after a++ : 1
a value after a++ : 2
a value:1
b value after ++a : 2
a value after ++a : 2
a value before decrement: 5
b value after a-- : 5
a value after a-- : 4
a value: 5
b value after --a : 4
a value after --a : 4
Type Conversion in C++
A type cast is basically a conversion from one type to another. There are two types of
type conversion. They are
1. Implicit Type Conversion
2. Explicit Type Conversion:
Page 17 of 96
Page 18 of 96
Syntax:
(type) expression
where type indicates the data type to which the final result is converted.
Example:
#include <iostream.h>
void main()
{
double x = 1.2;
// Explicit conversion from double to int
int sum = (int)x + 1;
cout << "Sum = " << sum;
}
Output:
Sum = 2
Advantages of Type Conversion:
This is done to take advantage of certain features of type hierarchies or type
representations.
It helps to compute expressions containing variables of different data types.
Control structures
C++ is too must able to perform different sets of actions depending on the situations. Many
times, we want a set of instructions to be executed is one situation, and an entirely different set of
instructions to be executed in one situation, and an entirely different set of instructions to be
executing in another situation. This kind of situation is dealt in c++ programs using a control
instruction can be implemented in C++ using:
1) Sequential statements (if, if else, if else if)
2) Selection statements (switch case, goto)
3) Iteration/Repetition statements (while, do while, for)
Page 19 of 96
2. if - else statements
3. nested if statements
4. if-else-if statements
5. switch statements
6. Jump Statements:
a. break
b. continue
c. goto
1.If
This is a one way conditional statement. It is used to execute a set of statements only when the
condition is TRUE or satisfied.
Syntax:
if (condition)
{
Statements;
}
Flowchart:
Example:
Page 20 of 96
#include< iostream.h>
void main( )
{
int x,y;
x=15;
y=13;
if (x > y )
{
cout << "x is greater than y";
}
}
2.If else
It is used to execute a set of statements only when the condition is TRUE. When the
condition is FALSE, it displays statements else part.
Syntax:
if(expression)
{
statement-block1;
}
else
{
statement-block2;
}
If the 'expression' is true or returns true, then the 'statement-block1' will get executed, else
'statement-block1' will be skipped and 'statement-block2' will be executed.
Flow Diagram
Example:
#include< iostream.h>
void main( )
{
int x,y;
x=15;
y=18;
if (x > y )
{
cout << "x is greater than y";
}
Page 21 of 96
else
{
cout << "y is greater than x";
}
}
Nested-if in C++:
The if statement with in another if is called Nested if/Ladder if Here a condition with in
another condition will be checked till it satisfies the condition.
Syntax:
if(expression)
{
if(expression1)
{
statement-block1;
}
else
{
statement-block2;
}
}
else
{
statement-block3;
}
Example:
include<iostream.h>
void main( )
{
int a,b,c;
cout << "enter 3 number";
cin >> a >> b >> c;
if(a > b)
{
if( a > c)
{
cout << "a is greatest";
}
else
{
cout << "c is greatest";
}
}
else
{
Page 22 of 96
if( b> c)
{
cout << "b is greatest";
}
else
{
cout << "c is greatest";
}
}
}
4. if-else-if statements
In this we may have to use more than if else statement is called if else if.
Syntax:
if(expression 1)
{
statement-block1;
}
else if(expression 2)
{
statement-block2;
}
else if(expression 3 )
{
statement-block3;
}
else
default-statement;
Example:
#include<iostream.h>
void main( )
{
int a;
cout << "enter a number";
cin >> a;
if( a%5==0 && a%8==0)
{
cout << "divisible by both 5 and 8";
}
else if( a%8==0 )
{
cout << "divisible by 8";
}
else if(a%5==0)
{
cout << "divisible by 5";
}
else
{
cout << "divisible by none";
}
Page 23 of 96
}
5. Switch Statement in C++
Switch case statements are a substitute for long if statements that compare a variable to several
integral values
The switch statement is a multiway branch statement. It provides an easy way to dispatch
execution to different parts of code based on the value of the expression.
Switch is a control statement that allows a value to change control of execution.
Syntax:
switch (n)
{
case 1:
Statements;
break;
case 2:
Statements;
break;
case 3:
Statements;
break;
case n:
Statements;
break;
default:
stamen;
}
Example:
#include <iostream.h>
void main ()
{
char grade = 'D';
switch(grade)
{
case 'A' :
cout << "Excellent!" << endl;
break;
case 'B' :
case 'C' :
cout << "Well done" << endl;
break;
case 'D' :
cout << "You passed" << endl;
break;
case 'F' :
cout << "Better try again" << endl;
break;
Page 24 of 96
default :
cout << "Invalid grade" << endl;
}
cout << "Your grade is " << grade << endl;
}
Loops in C++
In any programming language, loops are used to execute a set of statements repeatedly
until a particular condition is satisfied. Loop is nothing but a group of statements it is used to
execute a set of statements repeatedly or until a particular condition is being satisfied.
There are 3 methods by way of which we can repeat a part of a program
1) While loop
2) Do while loop
3) For loop
1. While loop:
A while loop statement repeatedly executes a target statement as long as a given
condition is true. It is a conditional entry loop. It is used execute a set of statements repeatedly
when the condition is TRUE, when the condition becomes FALSE it comes out of the loop.
Syntax
while(condition)
{
statement(s);
}
Here, statement(s) may be a single statement or a block of statements. The condition may be
any expression, and true is any non-zero value. The loop iterates while the condition is true.
Example:
#include <iostream.h>
void main ( )
{
int a = 10;
while( a < 20 )
{
cout << "value of a: " << a << endl;
a++;
Page 25 of 96
}
}
OUTPUT:
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19
Do while loop
In do while loops also the loop execution is terminated on the basis of test condition. The
main difference between do while loop and while loop is in do while loop the condition is tested
at the end of loop body, i.e do while loop is exit controlled whereas the other two loops are entry
controlled loops.
Note: In do while loop the loop body will execute at least once irrespective of test condition.
Syntax:
do
{
Statements;
Increments / decrement;
} while (Condition);
Difference between while & do while loop
While Do while
1. In this loop the condition is checked 1. In this loop the condition is checked
before the statements after the statements
2. The minimum no of execution of 2. The minimum no. of execution of
statements in while loop is zero statements in do while loop is one.
Example
#include <iostream.h>
void main ()
{
int a = 10;
do
{
cout << "value of a: " << a << endl;
a = a + 1;
} while( a < 20 );
}
OUTPUT:
Page 26 of 96
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19
For loop:
A for loop is a repetition control structure that allows you to efficiently write a loop that needs to
execute a specific number of times.
Syntax
for ( initialization; condition; increment / Decrement )
{
statement(s);
}
The initialization step is executed first, and only once. This step allows you to declare
and initialize any loop control variables. You are not required to put a statement here, as
long as a semicolon appears.
Next, the condition is evaluated. If it is true, the body of the loop is executed. If it is
false, the body of the loop does not execute and flow of control jumps to the next
statement just after the for loop.
After the body of the for loop executes, the flow of control jumps back up to the
increment statement. This statement can be left blank, as long as a semicolon appears
after the condition.
The condition is now evaluated again. If it is true, the loop executes and the process
repeats itself (body of loop, then increment step, and then again condition). After the
condition becomes false, the for loop terminates.
Page 27 of 96
Example:
// C++ program to illustrate for loop
#include <iostream.h>
void main()
{
for (int i = 1; i <= 10; i++)
{
cout << "Hello World\n";
}
}
OUTPUT:
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Nested loops: A loop with in another loop is called nested loop. Java supports all looping
statements have nested loops when the outer loop condition becomes true. It enters to the inner
loop. When inner loop executed for every termination of inner loop the condition will be
checked.
Labeled loops: in java user can give the labels to a block of statements. A label is a any valid
java variable name. to give a labeled to the loop place it before the loop with a colon. The labeled
loops are used to identify the range of loop.
Page 28 of 96
Syntax;
Loop name : for ( ) block name :
{ {
………….. ……………
………….. ……………
} }
Ex;
loop1: for (int i=0; i<=10; i++)
{
loop2: while(x<100)
{
y=i*x
if(y>500)
break loop1;
}
}
Data and functions are separated in C because it is Data and functions are encapsulated together
a procedural programming language. in form of an object in C++.
Page 29 of 96
C C++
intended.
Reference variables are not supported by C. Reference variables are supported by C++.
Virtual and friend functions are not supported by Virtual and friend functions are supported by
C. C++.
Functions in C++
Function is a group of statements that together perform a task. Every C++ program has at
least one function, which is main(), and all the most trivial programs can define additional
functions.
We can divide up your code into separate functions. How you divide up your code among
different functions is up to you, but logically the division usually is such that each function
performs a specific task.
A function declaration tells the compiler about a function's name, return type, and
parameters. A function definition provides the actual body of the function.
Page 30 of 96
The C++ standard library provides numerous built-in functions that your program can call. For
example, function strcat() to concatenate two strings, function memcpy() to copy one memory
location to another location and many more functions.
A function is known with various names like a method or a sub-routine or a procedure etc.
Defining a Function
return_type function_name( parameter list )
{
body of the function
}
A C++ function definition consists of a function header and a function body. Here are all the
parts of a function −
Return Type − A function may return a value. The return_type is the data type of the
value the function returns. Some functions perform the desired operations without
returning a value. In this case, the return_type is the keyword void.
Function Name − This is the actual name of the function. The function name and the
parameter list together constitute the function signature.
Parameters − A parameter is like a placeholder. When a function is invoked, you pass a
value to the parameter. This value is referred to as actual parameter or argument. The
parameter list refers to the type, order, and number of the parameters of a function.
Parameters are optional; that is, a function may contain no parameters.
Function Body − The function body contains a collection of statements that define what
the function does.
Example:
#include<iostream.h>
void sum(int x, int y)
{
int z;
z = x + y;
cout << z;
}
int main()
{
int a = 10;
int b = 20;
// calling the function with name 'sum'
sum (a, b);
}
Page 31 of 96
void calc(int x)
{
x = x + 10 ;
}
10
Call by Reference
In this we pass the address of the variable as arguments. In this case the formal parameter can be
taken as a reference or a pointer, in both the case they will change the values of the original
variable.
#include<iostream.h>
void calc(int *p);
void main()
{
int x = 10;
calc(&x); // passing address of x as argument
printf("%d", x);
}
void calc(int *p)
{
*p = *p + 10;
}
20
Function Overloading in C++
Function overloading is a feature in C++ where two or more functions can have the same
name but different parameters.
If any class have multiple functions with same names but different parameters then they
are said to be overloaded. Function overloading allows we use the same name for different
functions, to perform, either same or different functions in the same class.
Function overloading is usually used to enhance the readability of the program. If we
have to perform one single operation but with different number or types of arguments, then we
can simply overload the function.
Different ways to Overload a Function
1. By changing number of Arguments.
2. By having different types of argument.
By changing the Number of Arguments
In this way of function overloading, we define two functions with the same names but a
different number of parameters of the same type. For example, in the below-mentioned program,
we have made two sum() functions to return the sum of two and three integers.
int sum (int x, int y)
{
Page 33 of 96
Page 34 of 96
instructions. On the other hand, the OOP is all about creating objects that can interact with each
other, this makes it easier to develop programs in OOP as we can understand the relationship
between them.
1. Class
2. Object
3. Abstraction
4. Encapsulation
5. Polymorphism
6. Inheritance
1. Class:
A class is an abstract data type that groups the data members and associated functions. It can also
hide the data and functions if required. In other words class is a collection of variables, functions
and methods in a single unit is called as class.
A class specification consists of two parts.
i. Declaration of a class
ii. Definition of members of data and members functions of a class.
Syntax of class:
Class classname
{
Public/private:
Datatype variable1;
Datatype variable1;
Functiontype functionname(parameters)
{
----
---
}
};
The above syntax “Class” is a keyword used for to create a class.
2. Object:
An Object is an identifiable entity with some characteristics and behaviour. An Object is
an instance of a Class. When a class is defined, no memory is allocated but when it is instantiated
(i.e. an object is created) memory is allocated.
Page 35 of 96
Syntax:
Classname objectname=new classname( );
Or
Classname objectname;
Example:
class person
{
char name[20];
int id;
public:
void getdetails(){}
};
int main()
{
person p1=new ; // p1 is a object
}
3. Data Abstraction:
Abstraction is a process of hiding irrelevant details from user. For example, When We
send an SMS we just type the message, select the contact and click send, the phone shows we
that the message has been sent, what actually happens in background when we click send is
hidden from we as it is not relevant to us.
The definition of “Abstraction” can also be given as elimination of irrelevant information
and amplification of essential information. Abstraction is nothing but finding out what is
common among different things.
4. Encapsulation:
Encapsulation is the mechanism which binds together the code and the data. This
encapsulation prevents the code and data from being accessed by other code defined outside the
class. Encapsulation can be defined as wrapping up of data and methods in to a single unit known
as a class. A class defines the structure and behaviour (data and code) this is shared by all its
objects.
5. Inheritance:
Inheritance is a process in which acquires all the properties and behaviours from old class
to new class is called inheritance. In this process old class is called as “Parent Class” or “Base
Class” or Super Class” and new class is called as “Child Class” or “Derived Class” or “Sub
Class”.
Page 36 of 96
Base class
Derived class
ii. Multiple Inheritances: it having more than one base class and one derived class is called as
single inheritance.
Derived class
iii. Hierarchical Inheritances: it having only one base class and more than one derived class is
called as single inheritance.
-
Base class
iv. Multilevel Inheritances: in this process of deriving class from another derived class. A class
can inherit the properties and behaviours of another class which have already inherited the
properties and behaviour of some other class. Base class
Derived/ base
class
Page 37 ofDerived
96 class
Page 38 of 96
Structured Programming is less secure as there is Object Oriented Programming is more secure
no way of data hiding. as having data hiding feature.
Structured Programming can solve temperately Object Oriented Programming can solve any
complex programs. complex programs.
Structured Programming provides less reusability, Object Oriented Programming provides more
more function dependency. reusability, less function dependency.
Less abstraction and less flexibility. More abstraction and more flexibility.
Examples: C, FORTRAN, Pascal, Basic etc. Examples: C++, Java, Python, C# etc.
{
break;
}
}
if(no==i)
{
cout<<"\n"<<no<<" is a prime number";
}
else
{
cout<<"\n"<<no<<" is not a prime number";
}
}
2. Following is the program to check whether a number is armstrong or not.
#include<iostream.h>
void main()
{
int no, ld, nn=0, cn;
cout<<"Enter a number to be checked : "
cin>>no;
cn==no;
while(no > 0)
{
ld=no%10;
nn=nn+ld*ld*ld;
no=n/10;
}
if(nn==cn)
{
cout<<"\n"<<cn<<" is an armstrong number";
}
else
{
cout<<"\n"<<cn<<" is not an armstrong number";
}
}
3. Following is the program to find factorial of a given number.
#include<iostream.h>
#include<conio.h>
void main()
{
int i, n1, factorial=1;
clrscr() ;
cout<<"Enter the number to find it's factorial : " ;
cin>>n1 ;
for(a=1;a<=n1;a++)
{
factorial*=a;
Page 40 of 96
}
if(n1==0)
{
cout<<"\nThe factorial is : 1";
}
else
{
cout<<"\nThe factorial is : "<<factorial;
}
getch() ;
}
4. Following is the program to find greatest of three numbers.
#include<iostream.h>
#include<conio.h>
void main()
{
float n1, n2, n3;
cout << "Enter three numbers: ";
cin >> n1 >> n2 >> n3;
if (n1 >= n2 && n1 >= n3)
{
cout << "Largest number: " << n1;
}
if(n2 >= n1 && n2 >= n3)
{
cout << "Largest number: " << n2;
}
if(n3 >= n1 && n3 >= n2)
{
cout << "Largest number: " << n3;
}
getch();
}
5. Following is the program to swap two numbers with the help of a temporary variable.
#include<iostream.h>
#include<conio.h>
void main()
{
int a,b,x;
cout<<"Enter a and b:\n";
cin>>a>>b;
cout<<"Before swapping"<<endl<<"Value of a= "<<a<<endl<<"Value of b=
"<<b<<endl;
{
x=a;
Page 41 of 96
a=b;
b=x;
cout<<"After swapping"<<endl<<"Value of a= "<<a<<endl<<"Value of b=
"<<b<<endl;
}
getch();
}
6. Following is a program to check whether a string is palindrome or not.
#include<iostream.h>
#include<string.h>
void main()
{
char string[50];
int len, i, x, flag=0;
cout<<"Enter a String(max 49 characters): ";
cin.getline(string,50);
len = strlen(string);
for(i=0, x=len-1;i<=len/2;i++, x--)
{
if(string[i]!=string[x])
{
flag=1;
break;
}
}
if(flag==0)
{
cout<<"\n\nString is palindrome";
}
else
{
cout<<"\n\nString is not a palindrome";
}
}
Page 42 of 96
UNIT 2
Classes: Introduction, Defining an Instance of a Class, Why Have Private Members? Separating
Constructors, Private Member Functions, Arrays of Objects, Instance and Static Members,
Conversion, Aggregation.
Page 43 of 96
attributes of a class are defined by variables along with data field and methods. A class contain
two types of member variables (variable types) namely data members and member functions.
Syntax:
Class class-Name
{
Public / Private:
Datatype variablename1;
Datatype variablename2;
Datatype variablename3;
Public / Private:
Member Function Declaration;
}
Example:
Consider the below example in which student is a class with its attributes defined in it.
Class student
{
Public:
int RollNo;
char Name[20];
char deptname[20];
public:
student( )
{
RollNo=101;
Strcpy(Name,”niveditha”);
Strcpy(deptname,”CA”);
}
Void display( )
{
Cout<<”Roll Numberis :”<<RollNo;
Cout<<”Student Name us :”<<Name;
Cout<<”Student Department is :”<<deptname;
}
};
In the above Example student is the class, data members are RollNo, Name and
deptName, Constructor is student( ), class methods is display( );
Declaration of class member Functions or Methods:
A method is a self-contained block of code that perform a specific well defined tasks. It is
also called as functions.
Page 45 of 96
Objects:
An object is an instance of a class which is used to access the members of a class.
Page 46 of 96
Example:
Student stu;
Employee emp;
Method2: an object can be also declared as a Pointer variable.
Syntax:
Classname *Objectname;
Example:
Student *stu;
Employee *emp;
Example:
#include<iostream.h>
#include<conio.h>
Class Student
{
Public:
int RollNo;
char Name[20];
char deptname[20];
public:
student( )
{
RollNo=101;
Strcpy(Name,”niveditha”);
Strcpy(deptname,”CA”);
}
Void display( )
{
Cout<<”Roll Numberis :”<<RollNo;
Cout<<”Student Name us :”<<Name;
Cout<<”Student Department is :”<<deptname;
}
};
Void main( )
{
Student stu;
Clrscr( );
Stu.display();
getch( );
}
State, Identity and Behaviour of an Object
An object is an entity that holds State, Behaviour and Identity. A class defines an object.
Page 47 of 96
1. State:
State of any an object represents its properties as well as the values of these properties.
Generally the attributes of an object will define the object state based on the values.
Attribute is one of the feature of the object and is static. But the value the attribute will be
dynamic. Therefore by changing the attribute value objects state can be modified.
2. Identity:
Object identity will differentiate it from the other objects. For example a bank has number
of customers each with unique account number. In similar way an object in programming
language will have its own properties.
3. Behaviour:
The behaviour of an object represent how an object act and reacts to the external actions
with respect to state change and passed message. When any message is passed to an object a
method will get invoked. This will addition cause well defined behaviour and lead to change in
object state some of the operations that are performed by the client on object are as follows,
a. Modifier: it modifies the object state
b. Selector: it access the object state without modifying it.
c. Constructor: it creates an object and initializes its state.
d. Destructor: it destroy the object by releasing its memory.
Page 48 of 96
Types of Constructors:
There are four types of constructor in C++. They are
1) Default constructor or without Parameterized constructor
2) Parameterized constructor
3) Copy Constructor.
1. Default constructor or without Parameterized constructor
Default constructor is the constructor which doesn‟t take any argument. It has no
parameters. If no constructor is specified than a default constructor is called automatically. It
does not accept any argument.
Syntax:
Class classname
{
Public / private:
Members declarations;
Public / private:
Member function declarations;
Classnae( )
{
Statements;
}
};
Example:
#include <iostream.h>
class construct
{
public:
int a, b;
construct()
{
a = 10;
b = 20;
}
};
void main()
{
construct c;
cout << "a: " << c.a << endl << "b: " << c.b;
}
Output:
a: 10
b: 20
Page 49 of 96
2. Parameterized Constructors:
A constructor that takes arguments as its parameters is known as Parameterized
constructor. It is used to initialize the elements that take different values. Whenever objects are
declared then their initial values are passed as arguments to constructor function.
Syntax:
Class classname
{
Public / private:
Members declarations;
Public / private:
Member function declarations;
Classnae(parameter1, parameter2,…….. )
{
Statements;
}
};
Example:
#include <iostream.h>
class construct
{
public:
int a, b;
construct(int x,int y)
{
a = x;
b = y;
}
Public void display( )
{
Cout<<a value is”<<a;
Cout<<b value is”<<b;
};
void main()
{
construct c(10,20);
c.display( );
}
Output:
A value is 10
B value is 20
3. Copy Constructors:
A copy constructor is a member function which initializes an object using another object of the
same class. This constructor copies one object from the other sequentially during the object
declaration. This process of initializing is called copy initialization.
Page 50 of 96
#include <iostream.h>
class A
{
public:
int x;
A(int a) // parameterized constructor.
{
x=a;
}
A(A &i) // copy constructor
{
x = i.x;
}
};
void main( )
{
A a1(20); // Calling the parameterized constructor.
A a2(a1); // Calling the copy constructor.
cout<<a2.x;
}
Default parameter value or Default arguments in function definition
A default argument is a value provided in a function declaration that is automatically
assigned by the compiler if the caller of the function doesn‟t provide a value for the argument
with a default value.
Following is a simple C++ example to demonstrate the use of default arguments. We
don‟t have to write 3 sum functions, only one function works by using default values for 3rd and
4th arguments.
#include<iostream.h>
// A function with default arguments, it can be called with
// 2 arguments or 3 arguments or 4 arguments.
int sum(int x, int y, int z=0, int w=0)
{
return (x + y + z + w);
}
/* Driver program to test above function*/
void main()
{
cout << sum(10, 15) << endl;
cout << sum(10, 15, 25) << endl;
cout << sum(10, 15, 25, 30) << endl;
Page 51 of 96
}
Output:
25
50
80
Constructor Overloading in C++
In C++, We can have more than one constructor in a class with same name, as long as each has a
different list of arguments.This concept is known as Constructor Overloading and is quite similar
tofunction overloading.
Overloaded constructors essentially have the same name (exact name of the class) and differ by
number and type of arguments.
A constructor is called depending upon the number and type of arguments passed.
While creating the object, arguments must be passed to let compiler know, which
constructor needs to be called.
Example Program:
// C++ program to illustrate
// Constructor overloading
#include <iostream.h>
using namespace std;
class construct
{
public:
float area;
// Constructor with no parameters
construct()
{
area = 0;
}
// Constructor with two parameters
construct(int a, int b)
{
area = a * b;
}
void disp()
{
cout<< area<< endl;
}
};
void main()
{
// Constructor Overloading
// with two different constructors
Page 52 of 96
// of class name
construct obj1;
construct obj2( 10, 20);
obj1.disp();
obj2.disp();
}
C++ Operators Overloading
Operator overloading is an important concept in C++. It is a type of polymorphism in
which an operator is overloaded to give user defined meaning to it. Overloaded operator is used
to perform operation on user-defined data type. For example '+' operator can be overloaded to
perform addition on various data types, like for Integer, String(concatenation) etc.
Where the returnType is the type of value returned by the function. classname is the
name of the class. operator OperatorSymbol is an operator function where OperatorSymbol is
the operator being overloaded, and the Operator is the keyword.
Rules for Operator Overloading
Existing operators can only be overloaded, but the new operators cannot be overloaded.
Page 53 of 96
The overloaded operator contains at least one operand of the user-defined data type.
We cannot use friend function to overload certain operators. However, the member
function can be used to overload those operators.
When unary operators are overloaded through a member function take no explicit
arguments, but, if they are overloaded by a friend function, takes one argument.
When binary operators are overloaded through a member function takes one explicit
argument, and if they are overloaded through a friend function takes two explicit
arguments.
C++ Operators Overloading Example
#include <iostream.h>
class Test
{
private:
int num;
public:
Test()
{
Num=8;
}
void operator ++()
{
num = num+2;
}
void Print()
{
cout<<"The Count is: "<<num;
}
};
void main()
{
Test tt;
++tt; // calling of a function "void operator ++()"
tt.Print();
}
Output:
The Count is: 10
Page 54 of 96
D1.displayDistance();
-D2;
D2.displayDistance();
}
OUTPUT:
F: -11 I:-10
F: 5 I:-11
breadth = bre;
}
void setHeight( double hei )
{
height = hei;
}
// Overload + operator to add two Box objects.
Box operator+(const Box& b) {
Box box;
box.length = this->length + b.length;
box.breadth = this->breadth + b.breadth;
box.height = this->height + b.height;
return box;
}
};
// Main function for the program
int main() {
Box Box1; // Declare Box1 of type Box
Box Box2; // Declare Box2 of type Box
Box Box3; // Declare Box3 of type Box
double volume = 0.0; // Store the volume of a box here
// box 1 specification
Box1.setLength(6.0);
Box1.setBreadth(7.0);
Box1.setHeight(5.0);
// box 2 specification
Box2.setLength(12.0);
Box2.setBreadth(13.0);
Box2.setHeight(10.0);
// volume of box 1
volume = Box1.getVolume();
cout << "Volume of Box1 : " << volume <<endl;
// volume of box 2
volume = Box2.getVolume();
cout << "Volume of Box2 : " << volume <<endl;
Page 57 of 96
In the above declaration, the friend function is preceded by the keyword friend. The function can
be defined anywhere in the program like a normal C++ function. The function definition does not
use either the keyword friend or scope resolution operator.
Characteristics of a Friend function:
The function is not in the scope of the class to which it has been declared as a friend.
It cannot be called using the object as it is not in the scope of that class.
It can be invoked like a normal function without using the object.
It cannot access the member names directly and has to use an object name and dot
membership operator with the member name.
It can be declared either in the private or the public part.
C++ friend function Example
Let's see the simple example of C++ friend function used to print the length of a box.
#include <iostream>
using namespace std;
class Box
Page 58 of 96
{
private:
int length;
public:
Box(): length(0) { }
friend int printLength(Box); //friend function
};
int printLength(Box b)
{
b.length += 10;
return b.length;
}
int main()
{
Box b;
cout<<"Length of box: "<< printLength(b)<<endl;
return 0;
}
Output:
Length of box: 10
When the inline function is encountered, then the definition of the function is copied to it. In this
case, there is no control transfer which saves a lot of time and also decreases the overhead.
Let's understand through an example.
#include <iostream>
using namespace std;
inline int add(int a, int b)
{
return(a+b);
}
int main()
{
cout<<"Addition of 'a' and 'b' is:"<<add(2,3);A
return 0;
}
Page 60 of 96
UNIT 3
Inheritance: Introduction, Protected Members and Class Access, Base Class Access
Specification, Constructors and Destructors in Base and Derived Classes, Redefining Base Class
Functions, Class Hierarchies, Polymorphism and Virtual Member Functions, Abstract Base
C++ Streams: Stream Classes, Unformatted I/O Operations, Formatted I/O Operations.
Page 61 of 96
Inheritance in C++
The capability of a class to derive properties and characteristics from another class is
called Inheritance. Inheritance is one of the most important feature of Object Oriented
Programming. OR
The process of acquiring the properties and characteristics form old class to new class is
called as Inheritance. In this process old class is called as Super class or Parent class or Base
class. And new class is called as Sub class or Child class or Derived class.
Sub Class or Derived class or Child Class: The class that inherits properties from another class
is called Sub class or Derived Class or Child class..
Super Class or Parent Class or Base Class: The class whose properties are inherited by sub
class is called Base Class or Super class or Parent Class.
Types of Inheritance in C++
C++ supports five types of inheritance. They are
1. Single Inheritance
2. Multiple Inheritance
3. Multilevel Inheritance
4. Hierarchical Inheritance
5. Hybrid (Virtual) Inheritance
1. Single Inheritance: In single inheritance, a class is allowed to inherit from only one class.
i.e. one sub class is inherited by one base class only.
Syntax:
class subclass_name : access_mode base_class
{
//body of subclass
};
Page 62 of 96
Example:
#include <iostream.h>
class A
{
public:
A( )
{
cout<<"Constructor of A class"<<endl;
}
};
class B: public A
{
public:
B( )
{
cout<<"Constructor of B class";
}
};
void main( )
{
B obj; //Creating object of class B
}
Output:
Constructor of A class
Constructor of B class
2. Multiple Inheritances: Multiple Inheritance is a feature of C++ where a class can inherit from
more than one classes. i.e one sub class is inherited from more than one base classes.
Syntax:
class subclass_name : access_mode base_class1, access_mode base_class2, ....
{
//body of subclass
};
Page 63 of 96
}
OUTPUT:
Constructor of A class
Constructor of B class
Constructor of C class
3. Multilevel Inheritance: In this type of inheritance, a derived class is created from another
derived class. It process of deriving a class from another derived class. A class can inherit the
properties and behaviour of another class which have already inherited the properties and
behaviour of some other class.
Page 64 of 96
}
Output:
Constructor of A class
Constructor of B class
Constructor of C class
4. Hierarchical Inheritance: In this type of inheritance, more than one sub class is
inherited from a single base class. i.e. more than one derived class is created from a single base
class.
Page 65 of 96
Page 66 of 96
Page 67 of 96
Concept of Reusability
In OOP, The concept of inheritance provide the idea of reusability. This means that we
can add additional features to an existing class without modifying it. This is possible by deriving
a new class from the existing one. The new class will have the combined features of both
the classes. The real appeal and power of the inheritance mechanism is that it allows the
programmer to reuse a class that is almost, but not exactly, what he wants, and to tailor the class
in such a way that it does not introduce any undesirable side effects into the rest of the classes.
Polymorphism in C++
Polymorphism is one of the important OOPs Concept. It is a mechanism through which
one operation or a function can take many forms depending upon the type of objects. This is, a
single operator or function that can be used in many ways.
Consider an example for adding two variables,
Sum=x+y;
Here, x, y can be integer numbers..
Sum=2+5;
Or x, y can be float numbers
Sum=2.5+7.5;
The result of “Sum” depends upon the value passed to it.
Types of Polymorphism
In C++ having two types of polymorphism. They are
1. Compile time Polymorphism.
2. Runtime Polymorphism.
1. Compile time Polymorphism:
In Compile time polymorphism the most appropriate member function is called by
comparing the type and the number of arguments by the compiler at compiles time. It is also
known as Early Binding or Static Linking or Static binding.
#include<iostream.h>
#include<conio.h>
Class Add
{
Public:
Void Sum(int a, int b)
{
Cout<<a+b;
}
Void Sum(int a, int b, int a)
{
Page 69 of 96
Cout<<a+b+c;
}
};
Void main( )
{
Clrscr( );
Add obj;
obj.Sum(10,20);
obj.Sum(10,20,30);
getch( );
}
2. Runtime Polymorphism:
In this type of Polymorphism the most appropriate member function is called runtime.
i.e., while the program is executing and the linking of function with a class occur after
compilation. Hence it is called “Late Binding”. It is also known as “Dynamic Binding”. It is
implemented using virtual function and the Pointers to a Objects.
{
Public:
int z;
};
Class M : public Y,Z
{
Public:
int m;
};
Example:
#include<iostream.h>
#include<conio.h>
Class Base
{
Public:
int b;
};
Class D1 : public virtual Base
{
Public:
int d1;
};
Class D2 : public virtual Base
{
Public:
int d2;
};
Class D3 : public D1,D2
{
Public:
int d3;
Public:
Void getdata( )
{
Cout<<”enter the values for b, d1, d3, d3 = “;
Cin>>b>>d1>>d2>>d3;
}
Void putdata( )
{
Cout<<”b =”<<b;
Cout<<”d1=”<<d1;
Cout<<”d2=”<<d2;
Cout<<”d3=”<<d3;
}
};
Void main( )
{
Page 71 of 96
Clrscr( );
D3 obj;
obj.getdata( );
obj.putdata( );
getch( );
}
OUTPUT:
Enter values for b, d1, d2, d3= 20, 30, 45, 60
b= 20
d1= 30
d2= 45
d3= 60
Virtual Function in C++
Virtual is a keyword is used to completed Polymorphism and resolve the problem in
multipath inheritance. An object can inherit the properties of a derived class object which interns
inherit the properties of base class object. Problems arise while calling the inherited objects. Such
problems are resolved using virtual functions.
A function is made virtual by placing virtual keyword before function name. a virtual
function when defined in the base class can also be redefined by all the derived classes. It
provides one interface to have multiple forms. Several versions of virtual function are accessed
using the appropriate class objects pointed by the base pointer.
Rules for Virtual Functions
1. Virtual functions cannot be static and also cannot be a friend function of another class.
2. Virtual functions should be accessed using pointer or reference of base class type to achieve run
time polymorphism.
3. The prototype of virtual functions should be same in base as well as derived class.
4. They are always defined in base class and overridden in derived class. It is not mandatory for
derived class to override (or re-define the virtual function), in that case base class version of
function is used.
5. A class may have virtual destructor but it cannot have a virtual constructor.
Syntax:
Virtual returntype functionname( );
Example Program:
#include <iostream.h>
class base
{
public:
virtual void print()
Page 72 of 96
{
cout << "print base class" << endl;
}
void show()
{
cout << "show base class" << endl;
}
};
class derived : public base
{
public:
void print()
{
cout << "print derived class" << endl;
}
void show()
{
cout << "show derived class" << endl;
}
};
void main( )
{
base* bptr;
derived d;
bptr = &d;
bptr->print();
bptr->show();
}
Output:
print derived class
show base class
Page 73 of 96
3. Different virtual function versions can be executed by simply making the base – pointer to
point to different objects.
4. The dot ( . ) operator is used to access virtual functions like the ordinary member functions.
5. Virtual functions can act as friend function to some other classes.
Example:
#include<iostream.h>
class Base
{
int x;
public:
virtual void fun() = 0;
int getX()
{
return x;
}
};
class Derived: public Base
{
int y;
public:
void fun( )
{
cout << "fun() called";
}
};
void main( )
{
Derived d;
d.fun();
}
Output:
fun() called
Page 74 of 96
Abstract class:
Abstract class is used in situation, when we have partial set of implementation of methods
in a class. For example, consider a class have four methods. Out of four methods, we have an
implementation of two methods and we need derived class to implement other two methods. In
these kind of situations, we should use abstract class.
A virtual function will become pure virtual function when you append "=0" at the end of
declaration of virtual function.
A class with at least one pure virtual function or abstract function is called abstract class.
Pure virtual function is also known as abstract function.
We can't create an object of abstract class b'coz it has partial implementation of methods
Abstract function doesn't have body
We must implement all abstract functions in derived class.
public:
virtual void Display1()=0; //Pure virtual function or abstract function
virtual void Display2()=0; //Pure virtual function or abstract function
void Display3()
{
cout<<"\n\tThis is Display3() method of Base Class";
}
};
class DerivedClass : public BaseClass
{
public:
void Display1()
{
cout<<"\n\tThis is Display1() method of Derived Class";
}
void Display2()
{
cout<<"\n\tThis is Display2() method of Derived Class";
}
};
void main()
Page 75 of 96
{
DerivedClass D;
D.Display1(); // This will invoke Display1() method of Derived Class
D.Display2(); // This will invoke Display2() method of Derived Class
D.Display3(); // This will invoke Display3() method of Base Class
}
Output:
This is Display1() method of Derived Class
This is Display2() method of Derived Class
This is Display3() method of Base Class
ios class is topmost class in the stream classes hierarchy. It is the base class for istream,
ostream, and streambuf class.
istream and ostream serves the base classes for iostream class. The class istream is
used for input and ostream for the output.
Class ios is indirectly inherited to iostream class using istream and ostream. To avoid
the duplicity of data and member functions of ios class, it is declared as virtual base class
when inheriting in istream and ostream.
Facilities provided by these stream classes
1. The ios class: The ios class is responsible for providing all input and output facilities to
all other stream classes.
2. The istream class: This class is responsible for handling input stream. It provides
number of function for handling chars, strings and objects such as get, getline, read,
ignore, putback etc..
Page 76 of 96
Example:
#include <iostream.h>
void main()
{
char x;
cin.get(x);
cout << x;
}
3. The ostream class: This class is responsible for handling output stream. It provides number of function
for handling chars, strings and objects such as write, put etc..
Example:
#include <iostream.h>
void main()
{
char x;
cin.get(x);
cout.put(x);
}
4. The iostream: This class is responsible for handling both input and output stream as both istream
class and istream class is inherited into it. It provides function of both istream class and istream class
for handling chars, strings and objects such as get, getline, read, ignore, putback, put, write etc..
Example:
#include <iostream.h>
void main()
{
cout.write("geeksforgeeks", 5);
}
5. istream_withassign class: This class is variant of istream that allows object assigment. The
predefined object cin is an object of this class and thus may be reassigned at run time to a different
istream object.
6. ostream_withassign class: This class is variant of ostream that allows object assigment. The
predefined objects cout, cerr, clog are objects of this class and thus may be reassigned at run time to a
different ostream object.
No. Functions
Functions Description
Using this function, we can specify the width of a value to
width(int width)
be displayed in the output at the console.
Using this function, we can fill the unused white spaces in a
fill(char ch) value(to be printed at the console), with a character of our
choice.
Using this function, we can set the flags, which allow us to
setf(arg1, arg2)
display a value in a particular format.
peek() The function returns the next character from input stream,
without removing it from the stream.
The function skips over a number of characters, when taking
ignore(int num)
an input from the user at console.
This function appends a character(which was last read by
putback(char ch) get() function) back to the input stream.
Using this function, we can specify the number of
precision(int num_of_digts) digits(num_of_digits) to the right of decimal, to be printed
in the output.
In C++, we can read the input entered by a user at console using an object cin of istream
class and we can write the output at console using an object cout of ostream class. Through the
cin and cout objects, we can access the formatted I/O functions.
1. Using the output width() function
Using this function, we can specify the width of a value to be displayed in the output at
the console. Let's see the syntax of width() function -
width(int width);
Where, width is the value to be displayed in the output at the console.
2. Using the fill(), output function
Using this function, we can fill the unused white spaces in a value(to be printed at the
console), with a character of our choice Let's see the syntax of fill() function -
Page 78 of 96
fill(char ch);
Where, ch is a char value which fills the unused white spaces in a value.
3. Using the peek(), input function
The function returns the next character from input stream, without removing it from the
stream. Let's see the syntax of peek() function -
peek(void);
4. Using the ignore(), input function
The function skips over a number of characters, when taking an input from the user at
console. Let's see the syntax of ignore() function -
ignore(int num);
Where, num is the number of characters that will be skipped, when taking an input from the user
at console.
5. Using the output putback() function
This function appends a character(which was last read by get() function) back to the input
stream. Let's see the syntax of putback() function -
putback(char ch);
Where, ch is a char value appended back to the input stream.
6. Using the precision(), output function
Using this function, we can specify the number of digits to the right of decimal, to be printed in
the output at the console. Let's see the syntax of precision() function -
precision(int num_of_digits);
Where, num_of_digits is number of digits to the right of decimal, to be printed in the output at the
console.
C++ Unformatted Input / Output Functions
Un-formatted input/output functions are the simple and basic I/O functions of C++. They are the
means of the data transfer between the memory and the file in binary form. They can operate
only on the data type “char”
Un-formatted I/O functions:
Different functions in this category are follows,
1. getchar( )
2. putchar( )
3. gets( )
4. puts( )
Page 79 of 96
5. getch( )
6. putch( )
1. getchar( ): this function returns single character entered keyboard. No arguments are the
required for this function. By calling this function we can read a single character only.
Syntax:
Var=getchar( );
2. puthcar( ): this function displays a single character on an output device.
Syntax:
putchar(var );
3. gets( ): This function reads only an input string form values. But note read a single character
and numeric value from input.
Syntax:
gets(var);
4. puts( ): This function displays only string form values. But note displays a single character
and numeric values..
Syntax:
puts(var);
5. getch( ): this function is an un-formatted function defined in conio.h header file. It is an
input function that take single character as input and does not display (echo) it on screen.
6. putch( ): this function is an un-formatted function defined in conio.h header file. It is an
output function to display single alphanumeric character to the screen.
Programs:
Example for getchar( ) and putchar( )
#include<iostream.h>
#include<conio.h>
Void main( )
{
Char ch;
Clescr( );
Cout<<”enter a character”;
Ch=getchar( );
Cout<<”we entered a character”;
putchar(ch);
Page 80 of 96
getch( );
}
Example for ges( ) and puts( )
#include<iostream.h>
#include<conio.h>
Void main( )
{
Char a[25];
Clrscr( );
Cout<<”enter the string values”;
gets(a);
Cout<<”we entered string value is”;
puts(a);
getch( );
}
PROGRAMS
Single Inheritance Program:
#include<iostream.h>
#include<conio.h>
class staff
{
private:
char name[50];
int code;
public:
void getdata();
void display();
};
void staff::getdata()
Page 81 of 96
{
cout<<"Name:";
gets(name);
cout<<"Code:";
cin>>code;
}
void staff::display()
{
cout<<"Name:"<<name<<endl;
cout<<"Code:"<<code<<endl;
}
void typist::getdata()
{
cout<<"Speed:";
cin>>speed;
}
void typist::display()
{
cout<<"Speed:"<<speed<<endl;
}
void main()
{
typist t;
cout<<"Enter data"<<endl;
t.staff::getdata();
t.getdata();
cout<<endl<<"Display data"<<endl;
t.staff::display();
t.display();
getch();
}
Output
Enter data
Name:Roger Taylor
Code:13
Speed:46
Display data
Name:Roger Taylor
Code:13
Speed:46
Page 82 of 96
Page 83 of 96
Enter value of y= 3
Enter value of z= 3
Product= 18
Hierarchical Inheritance Program
#include <iostream.h>
class A //single base class
{
public:
int x, y;
void getdata()
{
cout << "\nEnter value of x and y:\n"; cin >> x >> y;
}
};
class B : public A //B is derived from class base
{
public:
void product()
{
cout << "\nProduct= " << x * y;
}
};
class C : public A //C is also derived from class base
{
public:
void sum()
{
cout << "\nSum= " << x + y;
}
};
void main()
{
B obj1; //object of derived class B
C obj2; //object of derived class C
obj1.getdata();
obj1.product();
obj2.getdata();
obj2.sum();
} //end of program
Output
void main()
{
C obj1; //object of derived class C
obj1.getx();
obj1.gety();
obj1.sum();
} //end of program
Output
enter value of x: 5
enter value of y: 4
Sum = 9
Page 85 of 96
UNIT 4
Exception Handling with Classes, Multiple Exceptions, Extracting Data from the Exception
Overloading with Function Templates, Class Templates – Introduction, Defining Objects of the
Page 86 of 96
EXCEPTION HANDLING
EXCEPTION:
Rarely does a program run successfully at first attempt it is common to make mistake
while developing as well as typing a program. To produce expected errors, result errors than to
go a wrong program. Errors and abnormal conditions arising while executing a program its type
of error is called as “Exception”.
Types of Errors (Exceptions):
In C++ programming language, errors may be identified into two types. They are
1. Compile-time Errors (Syntax Errors).
2. Run-time Errors (Logical Errors).
1. Compile-time Errors (Syntax Errors):
All syntax errors detected and displayed by the C++ compiler. Therefore these errors are
known as “Compile-time Errors”.
The most common errors are listed below.
i. Missing semicolons.
ii. Missing or mismatch of brackets
iii. Misspelling identifiers and keywords.
iv. Missing double quotes in a string.
v. Use of undeclared variables.
Example:
#include<iostream.h>
Void main( )
{
int a,b,c;
cout<<”enter a,b values”;
cin>>a>>b;
c=a+b
cout<<”c values is”<<c;
}
The above program saves as “addition.cpp”. After saving a program than we can compile
the above program, to display one error. Its error as follow “semicolon is missing”.
2. Run-time Errors (Logical Errors):
In C++, after compiling the C++ program, there is no compile time error, than we can run it. In
that time running a program to display the some errors are known as Run-time Errors.
Reasons for Run-time Errors Occurrence:
i. Division-by zero condition
Page 87 of 96
Exception Handling:
In C++, a programme having some Exception (Errors), I that time we cannot handle the
program, that means a program is a abnormal condition which occurs during execution of
program when C++ handled that type of exception program by using Exception handling.
In C++ handled Exception by using 3 keywords.
try
catch
throw
1. Try:
Try is a keyword that is used to detect the exception i.e., run-time error. The statements that may
cause exception are saved inside the try block. The general syntax of try block is as follow
try
{
Statements of code;
------------------------
Throw exception;
}
2. Catch:
The catch block handles an exception thrown by the try block. It defines an action to be
taken when a run-time error occurs. The general syntax of catch block as follows
catch(type arguments)
{
Statement;
}
Page 88 of 96
A catch block takes arguments as an exception. These arguments specify the type of an exception
that can be handled by the catch block. When an exception is thrown the control goes to catch
block. If the type of an exception thrown matches the argument then the catch block is executed,
otherwise the program terminates abnormally. If no exception is thrown from the try block then
the catch block is skipped and control goes immediately to the next statement following the catch
block.
3. Throw:
An exception detected in try block is thrown using “throw” keyword. An exception can be
thrown using throw statement in following number if ways.
throw(exception);
throw exception;
throw;
Example:
#include <iostream.h>
void main()
{
int a=10, b=0, c;
try
{
if(b == 0)
{
throw "Division by zero not possible";
c = a/b;
}
}
catch(char* ex)
{
cout<<ex;
}
}
Page 89 of 96
Template:
Templates in c++ is defined as a blueprint or formula for creating a generic class or a function.
To simply put, you can create a single function or single class to work with different data types
using templates.
Page 90 of 96
C++ template is also known as generic functions or classes which is a very powerful feature in
c++. A keyword “template” in c++ is used for the template‟s syntax and angled bracket in a
parameter (t), which defines the data type variable.
How do templates work in C++?
Templates in c++ works in such a way that it gets expanded at compiler time, just like macros
and allows a function or class to work on different data types without being rewritten.
Types of Templates in C++
There are two types of templates in C++
Function template
Class templates
return a;
}
int main()
count<<func(15,8),,endl;//func(int,int);
count,,func('p','q'),,endl;//func(char,char);
count<<func(7.5,9.2),,endl;//func(double,double)
return();
}
Output:
15
p
7.5
Class template in c++
The class template in c++ is like function templates. They are known as generic templates. They
define a family of classes in C++.
Syntax of Class Template
template<class Ttype>
class class_name
{
//class body;
}
Here Ttype is a placeholder type name, which will be specified when a class instantiated.
The Ttype can be used inside the body of the class.
Class template in c++ example:
#include<iostream.h>
template <class C>
class A{
private;
C,a,b;
public:
A(Cx,Cy){
a=x;
b=y;
}
void show()
Page 92 of 96
}
count<<"The Addition of"<<a<<"and"<<b<<"is"<<add()<<endl;
}
C add(){
C c=a+b;
return c;
}
};
int main(){
Aaddint(8,6);
Aaddfloat(3.5,2.6);
Aaaddouble(2.156,5.234);
Aaddint.show();
cout<<endl;
adddouble.show();
count<<endl;
return 0;
}
Output:
The addition of 8 and 6 is 14
Addition of 3.5 and 2.6 is 6.1
The addition of 2.156 and 5.234 is 7.390
Page 93 of 96
void square(int a)
{
cout << "Square of " << a << " is " << a * a
<< endl;
}
// Function to calculate square
void square(double a)
{
cout << "Square of " << a
<< " is " << a * a
<< endl;
}
int main()
{
// Function Call for side as
// 9 i.e., integer
square(9);
// Function Call for side as
// 2.25 i.e., double
square(2.25);
return 0;
}
Output:
Square of 9 is 81
Square of 2.25 is 5.0625
Explanation:
In the above code, the square is overloaded with different parameters.
The function square can be overloaded with other arguments too, which requires the
same name and different arguments every time.
To reduce these efforts, C++ has introduced a generic type called function template.
Page 94 of 96
Function Template: The function template has the same syntax as a regular function, but it
starts with a keyword template followed by template parameters enclosed inside angular
brackets <>.
template <class T>
T functionName(T arguments)
{
// Function definition
………. …… ….. …….
}
where, T is template argument accepting different arguments and class is a keyword.
Template Function Overloading:
The name of the function templates are the same but called with different arguments is
known as function template overloading.
If the function template is with the ordinary template, the name of the function remains
the same but the number of parameters differs.
When a function template is overloaded with a non-template function, the function name
remains the same but the function‟s arguments are unlike.
Below is the program to illustrate overloading of template function using an explicit function:
// C++ program to illustrate overloading
// of template function using an
// explicit function
#include <iostream.h >
// Template declaration
template <class T>
// Template overloading of function
void display(T t1)
{
cout << "Displaying Template: "
<< t1 << "\n";
}
// Template overloading of function
void display(int t1)
Page 95 of 96
{
cout << "Explicitly display: "
<< t1 << "\n";
}
// Driver Code
int main()
{
// Function Call with a
// different arguments
display(200);
display(12.40);
display('G');
return 0;
}
Output:
Explicitly display: 200
Displaying Template: 12.4
Displaying Template: G
Page 96 of 96