bcom-4th-sem-c-all-unit-final-notes
bcom-4th-sem-c-all-unit-final-notes
Unit - 1
Object oriented Programming
Object oriented programming is a way of solving complex problems by breaking them
into smaller problems using objects. Before Object Oriented Programming (commonly referred
as OOP), programs were written in procedural language, they were nothing but a long list of
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)
{
----
---
}
};
Page 1 of 99
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
Page 2 of 99
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”.
In c++ having 6 types of Inheritance technique. They are
i. Single Inheritance
ii. Multiple Inheritance
iii. Multilevel Inheritance
vi. Hierarchical Inheritance
v. Hybrid Inheritance
i. Single Inheritance: it having only one base class and one derived class is called as single
inheritance.
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
Page 3 of 99
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
Derived class
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.
Page 5 of 99
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.
Structure of C++ Program: or Layout of C++ Program
C++ Programming language is most popular language after C Programming language.
C++ is first Object oriented programming language. We have summarize structure of C++
Program in the following Picture –
Page 6 of 99
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;
}
Page 7 of 99
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
const float short unsigned
continue for signed void
default goto sizeof volatile
do if static while
While in C++ there are 31 additional keywords other than C Keywords they are:
asm bool catch class
const_cast delete dynamic_cast explicit
export false friend inline
mutable namespace new operator
private protected public reinterpret_cast
static_cast template this throw
true try typeid typename
using virtual wchar_t
Page 8 of 99
Identifiers: Identifiers are used as the general terminology for naming of variables,
functions and arrays. These are user defined names consisting of arbitrarily long sequence
of letters and digits with either a letter or the underscore(_) as a first character. Identifier
names must differ in spelling and case from any keywords. You cannot use keywords as
identifiers; they are reserved for special use. Once declared, you can use the identifier in
later program statements to refer to the associated value. A special kind of identifier,
called a statement label, can be used in goto statements.
There are certain rules that should be followed while naming c identifiers:
They must begin with a letter or underscore(_).
They must consist of only letters, digits, or underscore. No other special character is
allowed.
It should not be a keyword.
It must not contain white space.
It should be up to 31 characters long as only first 31 characters are significant.
3. Constants: Constants are also like normal variables. But, only difference is, their values can
not be modified by the program once they are defined. Constants refer to fixed values. They are
also called as literals.
Constants may belong to any of the data type.
Syntax:
const data_type variable_name; (or) const data_type *variable_name;
Types of Constants:
1. Integer constants – Example: 0, 1, 1218, 12482
2. Real or Floating point constants – Example: 0.0, 1203.03, 30486.184
3. Octal & Hexadecimal constants – Example: octal: (013 )8 = (11)10, Hexadecimal: (013)16
= (19)10
4. Character constants -Example: „a‟, „A‟, „z‟
5. String constants -Example: “GeeksforGeeks”
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”;
Page 9 of 99
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
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(?:).
Page 10 of 99
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 11 of 99
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 −
typedef type newname;
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 −
Page 12 of 99
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
3. Logical Operators
4. Bit-wise Operators
5. Unary Operators
6. Ternary Operator conditional operators
7. Assignment Operators
8. Special Operator
Page 13 of 99
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;
div=a/b;
cout<<”Division value is”<<div;
rem=a%b;
cout<<”Remainder value is”<<rem;
getch( );
}
Page 14 of 99
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 –
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 −
Page 15 of 99
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.
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.
Page 16 of 99
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.
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.
Page 17 of 99
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 18 of 99
1. increment
It is used to increment the value of the variable by 1. The increment can be done in two ways:
1. prefix increment
In this method, the operator preceeds the operand (e.g., ++a). The value of operand will
be incremented before it is used.
int a = 1;
int b = ++a; // b = 2
2. postfix increment
In this method, the operator follows the operand (e.g., a++). The value operand will be
incremented after it is used.
int a = 1;
int b = a++; // b = 1
int c = a; // c = 2
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()
{
// Post increment
int a = 1;
cout << "a value: " << a << endl;
Page 19 of 99
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
Page 20 of 99
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)
1. Decision Making in C / C++ (if , if..else, Nested if, if-else-if ) or Sequential
statements
Decision making is about deciding the order of execution of statements based on certain
conditions or repeat a group of statements until certain specified conditions are met. C++ handles
decision-making by supporting the following statements,
Decision making statements in programming languages decides the direction of flow of program
execution. Decision making statements available in C++ are:
1. if statement
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
Page 21 of 99
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:
#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.
Page 22 of 99
Flow Diagram
Example:
#include< iostream.h>
void main( )
{
int x,y;
x=15;
y=18;
if (x > y )
{
cout << "x is greater than y";
}
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;
}
Page 23 of 99
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
{
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;
Page 24 of 99
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";
}
}
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;
}
Page 25 of 99
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;
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);
}
Page 26 of 99
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++;
}
}
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);
Page 27 of 99
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:
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.
Page 28 of 99
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.
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
Page 29 of 99
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.
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;
}
}
Page 30 of 99
C C++
C++ is known as hybrid language because
For the development of code, C supports
C++ supports both procedural and object
procedural programming.
oriented programming paradigms.
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++.
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++.
Page 31 of 99
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.
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.
Page 32 of 99
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);
}
arguments to the function sum, and x and y
are parameters which will hold values of a and b to perform the required operation inside the
function.
Function body: is the part where the code statements are written.
1. Call by Value
2. Call by Reference
Call by Value
In this calling technique we pass the values of arguments which are stored or copied into
the formal parameters of functions. Hence, the original values are unchanged only the parameters
inside function changes.
#include<iostream.h>
void calc(int x);
void main()
{
int x = 10;
calc(x);
printf("%d", x);
}
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
C++ Programs
1. Following is the program to check whether a number is prime or not.
#include<iostream.h>
void main()
{
int no, i;
cout<<"Enter a number to be checked (greater than 2) : ";
cin>>no;
for(i=2;i<no;i++)
{
Page 34 of 99
if(no%i==0)
{
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";
}
}
Page 35 of 99
{
factorial*=a;
}
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;
Page 36 of 99
UNIT 2
Encapsulation in C++
In normal terms Encapsulation is defined as wrapping up of data and information under a single unit.
In Object Oriented Programming, Encapsulation is defined as binding together the data and the functions
that manipulates them.
Encapsulation represents the information of variables (attributes) in terms of data and,
methods (functions) and its operations in terms of purpose.
Encapsulation is the process of combining data and function into a single unit called
class.
Encapsulation is a powerful feature that leads to information hiding and abstract data
type.
They encapsulate all the essential properties of the object that are to be created.
Using the method of encapsulation the programmer cannot access the class directly.
Encapsulation also lead to data abstraction or hiding. As using encapsulation also hides the data.
In the above example the data of any of the section like sales, finance or accounts is hidden from
any other section.
Example:
class class_name
{
private:
datatype member_variables;
datatype member_functions;
public:
datatype member_variables;
datatype member_functions;
};
main()
{
class_name objectname1, objectname;
}
Page 38 of 99
Page 39 of 99
Obj.Get();
Obj.Display();
getch()
}
Abstract Data Types (ADT)
Abstract data type is a data type that allows the programmer to use it without
concentrating on the details of its implementation.
A class can be treated as an abstract data type by separating its specifications from the
implementation of its operations.
i. Considering and placing all the member variables in the private section of the class.
ii. Placing all the needed operations in the public section and describing the ways of using
these member functions.
iii. Considering all the helping functions as private member functions and placing them in
private section of the class.
Public:
Void setdata( );
Void getdata(int);
Void display();
Void area();
Void perimeter();
};
The example, class is a keyword and circle is a name of the class. The member variable
radius is declared in public section. And member functions are declared as in public section. The
public is the access specifies or access modifiers to provide access to the class members and is
terminated by semicolon (;). The class is enclosed within curly bracket and followed by
semicolon (;).
Declaration of class member variable:
A class in C++ program contain some information such as class member variable and
member functions. The member variables of a class are also called as class attributes. The
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”);
Page 41 of 99
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.
Define a Method or function:
The data contained in the class is manipulated by methods. They are defined in the class below
the instance variable.
Syntax:
Functiontype functionName(parameter list)
{
Statement1;
Statement2;
Statement3;
Return statement;
}
Here functiontype determine the type of value the method returns. The functionname is the name
of the method and the parameter list contain the data types and variable which will be passes to
the method as input.
Example:
Class sum
{
Public:
int x,y;
public:
int compute( )
{
int res=x+y;
return res;
}
};
Page 42 of 99
The above method compute( ) is embedded in class. It can also be defined outside the
class or in the main method. But the method gets executed only when it is called..
Objects:
An object is an instance of a class which is used to access the members of a class.
Page 43 of 99
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.
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 44 of 99
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
Page 45 of 99
{
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
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;
Page 46 of 99
};
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.
#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.
Page 47 of 99
#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);
}
Page 48 of 99
Syntax:
Pointer_variable = new datatype;
Example:
Ptr=new int;
Here “Ptr” is a pointer variable of type int created by using a new operator.
The allocated memory is large such that the object can be accommodated for specified
data type. If the requested memory is not available then it either return a “NULL” pointer or an
exception (error) is generated. But, usually in C++, it generates an exception in case of
unsuccessful allocation request.
“delete” Operator:
The delete operator is used to deallocate. It release the memory which was allocated by the new
operator through in pointer. The memory is released then it can be utilized by some other objects.
Syntax:
delete pointer_variable;
Example:
delete Ptr;
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:
Page 49 of 99
Page 50 of 99
UNIT 3
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)
{
cout << x+y;
}
int sum(int x, int y, int z)
{
cout << x+y+z;
}
int main()
{
sum (10, 20);
sum(10, 20, 30);
}
Function Overloading: Different Datatype of Arguments
In this type of overloading we define two or more functions with same name and same
number of parameters, but the type of parameter is different. For example in this program, we
Page 51 of 99
have two sum() function, first one gets two integer arguments and second one gets two double
arguments.
int sum(int x, int y)
{
cout<< x+y;
}
double sum(double x, double y)
{
cout << x+y;
}
int main()
{
sum (10,20);
sum(10.5,20.5);
}
30 31.0
Constructor Overloading
Constructor can be overloaded in a similar way as function overloading. Overloaded
constructors have the same name (name of the class) but different number of arguments.
Depending upon the number and type of arguments passed, specific constructor is called. Since,
there are multiple constructors present, argument to the constructor should also be passed while
creating an object.
// Source Code to demonstrate the working of overloaded constructors
#include <iostream.h>
class Area
{
private:
int length;
int breadth;
public:
// Constructor with no arguments
Area()
{
length=5;
breadth=2;
Page 52 of 99
}
// Constructor with two arguments
Area(int l, int b)
{
Length=ll;
Breadth=b;
}
void GetLength()
{
cout << "Enter length and breadth respectively: ";
cin >> length >> breadth;
}
int AreaCalculation()
{
return length * breadth;
}
void DisplayArea(int temp)
{
cout << "Area: " << temp << endl;
}
};
void main()
{
Area A1;
Area A2(2, 1);
int temp;
cout << "Default Area when no argument is passed." << endl;
temp = A1.AreaCalculation();
A1.DisplayArea(temp);
cout << "Area when (2,1) is passed as argument." << endl;
temp = A2.AreaCalculation();
A2.DisplayArea(temp);
}
Page 53 of 99
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.
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.
Page 54 of 99
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.
OUTPUT:
F: -11 I:-10
F: 5 I:-11
Page 57 of 99
// volume of box 3
volume = Box3.getVolume();
cout << "Volume of Box3 : " << volume <<endl;
return 0;
}
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:
1. Implicit Type Conversion: It is also known as „automatic type conversion‟. In implicit
conversion, the compiler carries out the conversions from one data type to another whenever an
expression has more than one data type. In order to prevent loss of data, all the variables of the
other data types are converted to the largest data type.
Done by the compiler on its own, without any external trigger from the user.
Generally takes place when in an expression more than one data type is present. In such
condition type conversion (type promotion) takes place to avoid loss of data.
All the data types of the variables are upgraded to the data type of the variable with
largest data type.
bool -> char -> short int -> int ->
unsigned int -> long -> unsigned ->
long long -> float -> double -> long double
It is possible for implicit conversions to lose information, signs can be lost (when signed
is implicitly converted to unsigned), and overflow can occur (when long long is implicitly
converted to float).
Example of Type Implicit Conversion:
#include <iostream.h>
void main()
{
int x = 10; // integer x
char y = 'a'; // character c
// y implicitly converted to int. ASCII
// value of 'a' is 97
x = x + y;
// x is implicitly converted to float
float z = x + 1.0;
cout << "x = " << x << endl << "y = " << y << endl<< "z = " << z << endl;
}
Page 59 of 99
Output:
x = 107
y=a
z = 108
2. Explicit Type Conversion: This process is also called type casting and it is user-defined.
Here the user can typecast the result to make it of a particular data type.
In C++, it can be done by two ways:
Converting by assignment: This is done by explicitly defining the required type in front
of the expression in parenthesis. This can be also considered as forceful casting.
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.
Page 60 of 99
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 61 of 99
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 62 of 99
}
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 63 of 99
}
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 64 of 99
Page 66 of 99
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.
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()
{
cout<<"Name:";
gets(name);
cout<<"Code:";
cin>>code;
}
void staff::display()
{
cout<<"Name:"<<name<<endl;
cout<<"Code:"<<code<<endl;
}
Page 68 of 99
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
};
class derive1 : public base // derived class from base class
{
public:
int y;
void readdata()
{
cout << "\nEnter value of y= "; cin >> y;
}
};
class derive2 : public derive1 // derived from class derive1
{
private:
int z;
public:
void indata()
{
cout << "\nEnter value of z= "; cin >> z;
}
void product()
{
cout << "\nProduct= " << x * y * z;
}
};
void main()
{
derive2 a; //object of derived class
a.getdata();
a.readdata();
a.indata();
a.product();
} //end of program
Output
Enter value of x= 2
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()
{
Page 70 of 99
Output
Page 71 of 99
class A
{
public:
int x;
void getx()
{
cout << "enter value of x: "; cin >> x;
}
};
class B
{
public:
int y;
void gety()
{
cout << "enter value of y: "; cin >> y;
}
};
class C : public A, public B //C is derived from class A and class B
{
public:
void sum()
{
cout << "Sum = " << x + y;
}
};
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 72 of 99
UNIT 4
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)
{
Cout<<a+b+c;
}
};
Void main( )
{
Clrscr( );
Add obj;
obj.Sum(10,20);
Page 73 of 99
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.
Page 74 of 99
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( )
{
Clrscr( );
D3 obj;
obj.getdata( );
obj.putdata( );
getch( );
}
OUTPUT:
Enter values for b, d1, d2, d3= 20, 30, 45, 60
b= 20
Page 75 of 99
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()
{
cout << "print base class" << endl;
}
void show()
{
cout << "show base class" << endl;
Page 76 of 99
}
};
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 77 of 99
Page 78 of 99
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..
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);
}
Page 79 of 99
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,
Page 80 of 99
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 -
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 -
Page 81 of 99
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( )
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..
Page 82 of 99
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);
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( );
}
Page 83 of 99
Manipulators:
Manipulators are helping functions that can modify the input/output stream. It does not
mean that we change the value of a variable, it only modifies the I/O stream using insertion (<<)
and extraction (>>) operators.
For example, if we want to print the hexadecimal value of 100 then we can print it as:
cout<<setbase(16)<<100
Types of Manipulators
There are various types of manipulators:
1. Manipulators without arguments: The most important manipulators defined by the
IOStream library are provided below.
o endl: It is defined in ostream. It is used to enter a new line and after entering a
new line it flushes (i.e. it forces all the output written on the screen or in the file)
the output stream.
o ws: It is defined in istream and is used to ignore the whitespaces in the string
sequence.
o ends: It is also defined in ostream and it inserts a null character into the output
stream. It typically works with std::ostrstream, when the associated output buffer
needs to be null-terminated to be processed as a C string.
o flush: It is also defined in ostream and it flushes the output stream i.e. it forces all
the output written on the screen or in the file. Without flush, the output would be
the same but may not appear in real-time.
#include <iostream.h>
#include <istream.h>
#include <sstream.h>
#include <string.h>
void main()
{
istringstream str(" Programmer");
string line;
getline(str >> std::ws, line);
cout << line << endl;
cout << "only a test" << flush;
cout << "\na";
cout << "b" << ends;
cout << "c" << endl;
}
Page 84 of 99
2. Manipulators with Arguments: Some of the manipulators are used with the argument
like setw (20), setfill („*‟) and many more. These all are defined in the header file. If we want to
use these manipulators then we must include this header file in our program.
For Example, you can use following manipulators to set minimum width and fill the empty space
with any character you want: std::cout << std::setw (6) << std::setfill (‟*‟);
Some important manipulators in <iomanip> are:
1. setw (val): It is used to sets the field width in output operations.
2. setfill (c): It is used to fill the character „c‟ on output stream.
3. setprecision (val): It sets val as the new value for the precision of floating-point
values.
4. setbase(val): It is used to set the numeric base value for numeric values.
5. setiosflags(flag): It is used to sets the format flags specified by parameter mask.
6. resetiosflags(m): It is used to resets the format flags specified by parameter mask.
Some important manipulators in <ios> are:
1. showpos: It forces to show a positive sign on positive numbers.
2. noshowpos: It forces not to write a positive sign on positive numbers.
3. showbase: It indicates numeric base of numeric values.
4. uppercase: It forces uppercase letters for numeric values.
5. nouppercase: It forces lowercase letters for numeric values.
6. fixed: It uses decimal notation for ?oating-point values.
7. scientific: It use scientific floating-point notation.
8. hex: Read and write hexadecimal values for integers and it works same as the
setbase(16).
9. dec: Read and write decimal values for integers i.e. setbase(10).
10. oct: Read and write octal values for integers i.e. setbase(10).
11. left: It adjust output to the left.
12. right: It adjust output to the right.
#include <iomanip.h>
#include <iostream.h>
void main()
{
double A = 100;
double B = 2001.5251;
double C = 201455.2646;
cout << hex << left << showbase << nouppercase;
cout << (long long)A << endl;
Page 85 of 99
cout << setbase(10) << right << setw(15) << setfill('_') <<
showpos
<< fixed << setprecision(2);
cout << B << endl;
cout << scientific << uppercase<< noshowpos << setprecision(9);
cout << C << endl;
}
Page 86 of 99
UNIT 5
EXCEPTION HANDLING AND DATA STRUCTURES IN C++
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.
Page 87 of 99
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
Page 88 of 99
catch(type arguments)
{
Statement;
}
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 99
Page 90 of 99
Data Structures
Data Structure:
The collection of data elements that are stored in memory is known as data structure. It
is considered as an efficient way of storing and organizing data inside the computer memory.
Types of Data Structure:
Data structures are divided into 2 types. They are
1. Linear Data Structure.
2. Non-Linear Data Structure.
1. Linear Data Structure:
A data structure in which all the data elements are stored in sequential manner is called
a Linear Data Structure. There are different types of Linear Data structure available in C++. They
are
1. Array
2. Stack
3. Queue
4. Linked List
1. Array: An Array is a collection of data elements with same data types. It is a variable that is
capable of holding fixed values in adjacent memory locations.
A0 A1 A2 -- --- --- --- --- --- An
Data
values 20 30 40 50 60 70 80 90 100
10
Stack in C++
A stack is a linear data structure that stores a set of elements in a sequential manner. In
stack, new elements can be inserted and the existing elements are deleted to/ form only single
end called TOP.
Stack is an ordered collection of homogeneous elements that follow LIFO (Last In First
Out) procedure in which, the element that is inserted last is deleted first. The various operations
performed on stack are as follow.
1. Push
2. Pop
Page 91 of 99
1. Push: the method of inserting an element onto a stack is called “PUSH” operation. It adds a
new element onto top of the stack.
2. POP: The method of deleting an element from a stack is called “POP” operation. It delete the
top most element present on the stack.
The position where the above two operations are performed is called “TOP”. The
numbers of elements which are present in stack are called “ITEMS”. The representation of stack
as follows below
Size of stack: 3
Refer to the following image for more information about the operations performed in the code.
Page 92 of 99
Stack Program:
#include <iostream.h>
int stack[100], n=100, top=-1;
void push(int val)
{
if(top>=n-1)
cout<<"Stack Overflow"<<endl;
else
{
top++;
stack[top]=val;
}
}
void pop()
{
if(top<=-1)
cout<<"Stack Underflow"<<endl;
else
{
cout<<"The popped element is "<< stack[top] <<endl;
top--;
}
}
void display()
{
if(top>=0)
{
cout<<"Stack elements are:";
for(int i=top; i>=0; i--)
{
cout<<stack[i]<<" ";
}
cout<<endl;
}
else
cout<<"Stack is empty";
}
int main()
{
int ch, val;
cout<<"1) Push in stack"<<endl;
cout<<"2) Pop from stack"<<endl;
cout<<"3) Display stack"<<endl;
cout<<"4) Exit"<<endl;
Page 93 of 99
do
{
cout<<"Enter choice: "<<endl;
cin>>ch;
switch(ch)
{
case 1:
cout<<"Enter value to be pushed:"<<endl;
cin>>val;
push(val);
break;
case 2:
pop();
break;
case 3:
display();
break;
case 4:
cout<<"Exit"<<endl;
break;
default:
cout<<"Invalid Choice"<<endl;
}
}
while(ch!=4);
return 0;
}
Queue Data Structure In C++
The queue is a basic data structure just like a stack. In contrast to stack that uses the LIFO
approach, queue uses the FIFO (first in, first out) approach. With this approach, the first item that is added
to the queue is the first item to be removed from the queue. Just like Stack, the queue is also a linear data
structure.
The queue can be viewed as a set or collection of elements as shown below. The elements are
arranged linearly.
We have two ends i.e. “front” and “rear” of the queue. When the queue is empty, then both the
pointers are set to -1.
Page 94 of 99
The “rear” end pointer is the place from where the elements are inserted in the queue. The
operation of adding /inserting elements in the queue is called “enqueue”.
The “front” end pointer is the place from where the elements are removed from the queue. The
operation to remove/delete elements from the queue is called “dequeue”.
When the rear pointer value is size-1, then we say that the queue is full. When the front is null,
then the queue is empty.
Basic Operations
The queue data structure includes the following operations:
EnQueue: Adds an item to the queue. Addition of an item to the queue is always done at the rear
of the queue.
DeQueue: Removes an item from the queue. An item is removed or de-queued always from the
front of the queue.
isEmpty: Checks if the queue is empty.
isFull: Checks if the queue is full.
peek: Gets an element at the front of the queue without removing it.
Enqueue
In this process, the following steps are performed:
Check if the queue is full.
If full, produce overflow error and exit.
Else, increment „rear‟.
Add an element to the location pointed by „rear‟.
Return success.
Dequeue
Dequeue operation consists of the following steps:
Check if the queue is empty.
If empty, display an underflow error and exit.
Else, the access element is pointed out by „front‟.
Increment the „front‟ to point to the next accessible data.
Return success.
Next, we will see a detailed illustration of insertion and deletion operations in queue.
Page 95 of 99
Illustration
This is an empty queue and thus we have rear and empty set to -1.
Next, we add 1 to the queue and as a result, the rear pointer moves ahead by one location.
In the next figure, we add element 2 to the queue by moving the rear pointer ahead by another
increment.
In the following figure, we add element 3 and move the rear pointer by 1.
At this point, the rear pointer has value 2 while the front pointer is at the 0th location.
Next, we delete the element pointed by the front pointer. As the front pointer is at 0, the element
that is deleted is 1.
Page 96 of 99
Thus the first element entered in the queue i.e. 1 happens to be the first element removed from
the queue. As a result, after the first dequeue, the front pointer now will be moved ahead t0 the
next location which is 1.
As shown above, the first node of the linked list is called “head” while the last node is called
“Tail”. As we see, the last node of the linked list will have its next pointer as null since it will not
have any memory address pointed to.
Since each node has a pointer to the next node, data items in the linked list need not be stored at
contiguous locations. The nodes can be scattered in the memory. We can access the nodes
anytime as each node will have an address of the next node.
We can add data items to the linked list as well as delete items from the list easily. Thus it is
possible to grow or shrink the linked list dynamically. There is no upper limit on how many data
items can be there in the linked list. So as long as memory is available, we can have as many data
items added to the linked list.
Apart from easy insertion and deletion, the linked list also doesn‟t waste memory space as we
need not specify beforehand how many items we need in the linked list. The only space taken by
linked list is for storing the pointer to the next node that adds a little overhead.
Page 97 of 99
Operations
Just like the other data structures, we can perform various operations for the linked list as
well. But unlike arrays, in which we can access the element using subscript directly even if it is
somewhere in between, we cannot do the same random access with a linked list.
In order to access any node, we need to traverse the linked list from the start and only
then we can access the desired node. Hence accessing the data randomly from the linked list
proves to be expensive.
We can perform various operations on a linked list as given below:
#1) Insertion
Insertion operation of linked list adds an item to the linked list. Though it may sound
simple, given the structure of the linked list, we know that whenever a data item is added to the
linked list, we need to change the next pointers of the previous and next nodes of the new item
that we have inserted. The second thing that we have to consider is the place where the new data
item is to be added.
There are three positions in the linked list where a data item can be added.
#1) At the beginning of the linked list
A linked list is shown below 2->4->6->8->10. If we want to add a new node 1, as the first node
of the list, then the head pointing to node 2 will now point to 1 and the next pointer of node 1 will
have a memory address of node 2 as shown in the below figure.
Page 98 of 99
Thus in the above diagram, we check if the given node is present. If it‟s present, we create a new
node f. Then we point the next pointer of node c to point to the new node f. The next pointer of
the node f now points to node d.
#3) At the end of the Linked List
In the third case, we add a new node at the end of the linked list. Consider we have the same
linked list a->b->c->d->e and we need to add a node f to the end of the list. The linked list will
look as shown below after adding the node.
Thus we create a new node f. Then the tail pointer pointing to null is pointed to f and the next
pointer of node f is pointed to null. We have implemented all three types of insert functions in the
below C++ program.
In C++, we can declare a linked list as a structure or as a class. Declaring linked list as a structure
is a traditional C-style declaration. A linked list as a class is used in modern C++, mostly while
using standard template library.
Page 99 of 99