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

bcom-4th-sem-c-all-unit-final-notes

The document provides comprehensive notes on Object Oriented Programming (OOP) concepts, particularly focusing on C++. It covers key OOP principles such as classes, objects, inheritance, encapsulation, polymorphism, and the differences between structured and object-oriented programming. Additionally, it includes a brief history of C++, its structure, and the classification of tokens used in programming.

Uploaded by

sumansri459
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

bcom-4th-sem-c-all-unit-final-notes

The document provides comprehensive notes on Object Oriented Programming (OOP) concepts, particularly focusing on C++. It covers key OOP principles such as classes, objects, inheritance, encapsulation, polymorphism, and the differences between structured and object-oriented programming. Additionally, it includes a brief history of C++, its structure, and the classification of tokens used in programming.

Uploaded by

sumansri459
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 100

lOMoARcPSD|51487838

BCOM 4th Sem C++ All unit final notes

Bussiness law (Palamuru University)

Scan to open on Studocu

Studocu is not sponsored or endorsed by any college or university


Downloaded by Sri Suman ([email protected])
lOMoARcPSD|51487838

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.

Object Oriented Programming Concepts (OOP Concepts)


In Object oriented programming we write programs using OOPs Concepts. There are
having 6 OOPs Concepts. They are

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

Downloaded by Sri Suman ([email protected])


lOMoARcPSD|51487838

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.
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

Page 2 of 99

Downloaded by Sri Suman ([email protected])


lOMoARcPSD|51487838

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.

Base class Base class Base class

Derived class

iii. Hierarchical Inheritances: it having only one base class and more than one derived class is
called as single inheritance.
-
Base class

Derived class Derived class Derived class

Page 3 of 99

Downloaded by Sri Suman ([email protected])


lOMoARcPSD|51487838

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

v. Hybrid Inheritance: it consists of combination of any two inheritance is called as Hybrid


Inheritance.
6. Polymorphism:
Polymorphism means that ability to take more than one forms. The concept of
polymorphism is often expressed as “one interfaces multiple methods”. This means that is
possible to create an interface that can be used for a group of related activities. With the use of
polymorphism, the complexity is reduced.

Object Oriented Programming Benefits (OOP Benefits)


 OOP provides a clear modular structure for programs.
 It is good for defining abstract data types.
 Implementation details are hidden from other modules and other modules has a clearly
defined interface.
 It is easy to maintain and modify existing code as new objects can be created with small
differences to existing ones.
 objects, methods, instance, message passing, inheritance are some important properties
provided by these particular languages
 Encapsulation, polymorphism, abstraction are also counts in these fundamentals of
programming language.
 It implements real life scenario.
 In OOP, programmer not only defines data types but also deals with operations applied
for data structures.

Features of Object Oriented Programming:


 More reliable software development is possible.
 Enhanced form of c programming language.
 The most important Feature is that it‟s procedural and object oriented nature.
Page 4 of 99

Downloaded by Sri Suman ([email protected])


lOMoARcPSD|51487838

 Much suitable for large projects.


 Fairly efficient languages.
 It has the feature of memory management.

Difference between Structured Programming and Object Oriented


Programming
Structured Programming Object Oriented Programming

Structured Programming is designed which


Object Oriented Programming is designed
focuses on process/ logical structure and then data
which focuses on data.
required for that process.

Structured programming follows top-down Object oriented programming follows


approach. bottom-up approach.

Structured Programming is also known as Object Oriented Programming supports


Modular Programming and a subset of inheritance, encapsulation, abstraction,
procedural programming language. polymorphism, etc.

In Structured Programming, Programs are divided In Object Oriented Programming, Programs


into small self-contained functions. are divided into small entities called objects.

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.

There is no access specifier in procedural Object oriented programming have access


programming. specifiers like private, public, protected etc.

In procedural programming, overloading is not Overloading is possible in object oriented


possible. programming.

In procedural programming, function is more In object oriented programming, data is more


important than data. important than function.

Procedural programming is based on unreal Object oriented programming is based on


world. real world.

Page 5 of 99

Downloaded by Sri Suman ([email protected])


lOMoARcPSD|51487838

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

Downloaded by Sri Suman ([email protected])


lOMoARcPSD|51487838

Section 1: Header File Declaration Section


1. Header files used in the program are listed here.
2. Header File provides Prototype declaration for different library functions.
3. We can also include user define header file.
4. Basically all pre-processor directives are written in this section.

Section 2: Global Declaration Section


1. Global Variables are declared here.
2. Global Declaration may include –
o Declaring Structure
o Declaring Class
o Declaring Variable

Section 3: Class Declaration Section


1. Actually this section can be considered as sub section for the global declaration section.
2. Class declaration and all methods of that class are defined here.

Section 4: Main Function


1. Each and every C++ program always starts with main function i.e., void main( ).
2. This is entry point for all the function. Each and every method is called indirectly through
main.
3. We can create class objects in the main.
4. Operating system calls this function automatically.

Section 5: Method Definition Section


1. This is optional section. Generally this method was used in C Programming.

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

Downloaded by Sri Suman ([email protected])


lOMoARcPSD|51487838

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

Downloaded by Sri Suman ([email protected])


lOMoARcPSD|51487838

 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

Downloaded by Sri Suman ([email protected])


lOMoARcPSD|51487838

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

Downloaded by Sri Suman ([email protected])


lOMoARcPSD|51487838

Data Types in C++


Data types define the type of data a variable can hold, for example an integer variable can
hold integer data, a character type variable can hold character data etc.
Data types in C++ are categorised in three groups: Built-in, user-defined and Derived

Built in data types or Primitive Data types

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.

Type size Range

int 4bytes -2147483648 to 2147483647

unsigned int 4bytes 0 to 4294967295

signed int 4bytes -2147483648 to 2147483647

short int 2bytes -32768 to 32767

unsigned short int Range 0 to 65,535

signed short int Range -32768 to 32767

long int 4bytes -2,147,483,648 to 2,147,483,647

signed long int 4bytes same as long int

unsigned long int 4bytes 0 to 4,294,967,295

Page 11 of 99

Downloaded by Sri Suman ([email protected])


lOMoARcPSD|51487838

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.

Type size Range

char 1byte -127 to 127 or 0 to 255

unsigned char 1byte 0 to 255

signed char 1byte -127 to 127

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.

Type size Range

float 4bytes +/- 3.4e +/- 38 (~7 digits)

double 8bytes +/- 1.7e +/- 308 (~15 digits)

long double 8bytes +/- 1.7e +/- 308 (~15 digits)

wchar_t 2 or 4 bytes 1 wide character

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

Downloaded by Sri Suman ([email protected])


lOMoARcPSD|51487838

enum enum-name { list of names } var-list;

Derived data types in C++


We have three types of derived-defined data types in C++
1. Array
2. Structure
3. Union
1. Arrays: An array is a collection of data elements (values) with similar data types is called as
an Array. Or C++ provides a data structure, the array, which stores a fixed-size sequential
collection of elements of the same type. An array is used to store a collection of data, but it is
often more useful to think of an array as a collection of variables of the same type.
2. Structure: A Structure is a collection of data elements (values) with different data types is
called as a Structure. To declaring a structure in c++ we are using the Keyword “struct”.
3. Union: A Union is a collection of data elements (values) with different data types is called as
a Union. To declaring a Union in c++ we are using the Keyword “union”.

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

Downloaded by Sri Suman ([email protected])


lOMoARcPSD|51487838

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

Operator Description Example

+ Adds two operands A + B will give 30

- Subtracts second operand from the first A - B will give -10

* Multiplies both operands A * B will give 200

/ Divides numerator by de-numerator B / A will give 2

Modulus Operator and remainder of after an


% B % A will give 0
integer division

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

Downloaded by Sri Suman ([email protected])


lOMoARcPSD|51487838

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 –

Operator Description Example

Checks if the values of two operands are


== equal or not, if yes then condition becomes (A == B) is not true.
true.

Checks if the values of two operands are


!= equal or not, if values are not equal then (A != B) is true.
condition becomes true.

Checks if the value of left operand is greater


> than the value of right operand, if yes then (A > B) is not true.
condition becomes true.

Checks if the value of left operand is less


< than the value of right operand, if yes then (A < B) is true.
condition becomes true.

Checks if the value of left operand is greater


>= than or equal to the value of right operand, if (A >= B) is not true.
yes then condition becomes true.

Checks if the value of left operand is less


<= than or equal to the value of right operand, if (A <= B) is true.
yes then condition becomes true.

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

Downloaded by Sri Suman ([email protected])


lOMoARcPSD|51487838

Operator Description Example

Called Logical AND operator. If both


&& the operands are non-zero, then (A && B) is false.
condition becomes true.

Called Logical OR Operator. If any of


|| the two operands is non-zero, then (A || B) is true.
condition becomes true.

Called Logical NOT Operator. Use to


reverses the logical state of its operand.
! !(A && B) is true.
If a condition is true, then Logical NOT
operator will make false.

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 AND Operator copies a bit to the result if it exists in both


&
operands.

| Binary OR Operator copies a bit if it exists in either operand.

Binary XOR Operator copies the bit if it is set in one operand but
^
not both.

Binary Ones Complement Operator is unary and has the effect of


~
'flipping' bits.

Binary Left Shift Operator. The left operands value is moved left
<<
by the number of bits specified by the right operand.

Binary Right Shift Operator. The left operands value is moved


>>
right 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

Downloaded by Sri Suman ([email protected])


lOMoARcPSD|51487838

The below table gives us a description of these assignment operators.

Operator Description

= Assigns the value of RHS operand to LHS operand

+= 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

Downloaded by Sri Suman ([email protected])


lOMoARcPSD|51487838

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( );
}

8. Unary operators in C++


Unary operator: are operators that act upon a single operand to produce a new value.
Types of unary operators:
1. increment(++)
2. decrement(- -)

Page 18 of 99

Downloaded by Sri Suman ([email protected])


lOMoARcPSD|51487838

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

Downloaded by Sri Suman ([email protected])


lOMoARcPSD|51487838

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

Downloaded by Sri Suman ([email protected])


lOMoARcPSD|51487838

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

Downloaded by Sri Suman ([email protected])


lOMoARcPSD|51487838

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

Downloaded by Sri Suman ([email protected])


lOMoARcPSD|51487838

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

Downloaded by Sri Suman ([email protected])


lOMoARcPSD|51487838

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

Downloaded by Sri Suman ([email protected])


lOMoARcPSD|51487838

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

Downloaded by Sri Suman ([email protected])


lOMoARcPSD|51487838

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

Downloaded by Sri Suman ([email protected])


lOMoARcPSD|51487838

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

Downloaded by Sri Suman ([email protected])


lOMoARcPSD|51487838

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:
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

Downloaded by Sri Suman ([email protected])


lOMoARcPSD|51487838

 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

Downloaded by Sri Suman ([email protected])


lOMoARcPSD|51487838

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;
}
}

Difference between C and C++


C C++
C was developed by Dennis Ritchie between the C++ was developed by Bjarne Stroustrup in
year 1969 and 1973 at AT&T Bell Labs. 1979.

C does no support polymorphism, encapsulation, C++ supports polymorphism, encapsulation,


and inheritance which means that C does not and inheritance because it is an object
support object oriented programming. oriented programming language.

C is a subset of C++. C++ is a superset of C.

C contains 32 keywords. C++ contains 52 keywords.

Page 30 of 99

Downloaded by Sri Suman ([email protected])


lOMoARcPSD|51487838

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++.

Data is hidden by the Encapsulation to ensure


C does not support information hiding. that data structures and operators are used as
intended.

Built-in & user-defined data types is


Built-in data types is supported in C.
supported in C++.

C is a function driven language because C is a C++ is an object driven language because it is


procedural programming language. an object oriented programming.

Function and operator overloading is not Function and operator overloading is


supported in C. supported by C++.

C is a function-driven language. C++ is an object-driven language

Functions can be used inside a structure in


Functions in C are not defined inside structures.
C++.

Namespace is used by C++, which avoid


Namespace features are not present inside the C.
name collisions.

Header file used by C is stdio.h. Header file used by C++ is iostream.h.

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++.

C does not support inheritance. C++ supports inheritance.

Exception handling is not supported by C. Exception handling is supported by C++.

scanf() and printf() functions are used for


cin and cout are used for input/output in C++.
input/output in C.

Page 31 of 99

Downloaded by Sri Suman ([email protected])


lOMoARcPSD|51487838

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

Downloaded by Sri Suman ([email protected])


lOMoARcPSD|51487838

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.

Declaring, Defining and Calling a Function


Function declaration, is done to tell the compiler about the existence of the function. Function's
return type, its name & parameter list is mentioned. Function body is written in its definition.
Lets understand this with help of an example.
#include < iostream.h>
int sum (int x, int y);
void main()
{
int a = 10;
int b = 20;
int c = sum (a, b); //calling the function
cout << c;
}
//defining the function
int sum (int x, int y)
{
return (x + y);
}
Here, initially the function is declared, without body. Then inside main() function it is called, as
the function returns sumation of two values, and variable c is there to store the result. Then, at
last, function is defined, where the body of function is specified. We can also, declare & define
the function together, but then it should be done before it is called.
Calling a Function
Functions are called by their names. If the function is without argument, it can be called directly
using its name. But for functions with arguments, we have two ways to call them,
Page 33 of 99

Downloaded by Sri Suman ([email protected])


lOMoARcPSD|51487838

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

Downloaded by Sri Suman ([email protected])


lOMoARcPSD|51487838

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";
}
}

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++)

Page 35 of 99

Downloaded by Sri Suman ([email protected])


lOMoARcPSD|51487838

{
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

Downloaded by Sri Suman ([email protected])


lOMoARcPSD|51487838

cout<<"Before swapping"<<endl<<"Value of a= "<<a<<endl<<"Value of b=


"<<b<<endl;
{
x=a;
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 37 of 99

Downloaded by Sri Suman ([email protected])


lOMoARcPSD|51487838

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

Downloaded by Sri Suman ([email protected])


lOMoARcPSD|51487838

Features and Advantages of Data Encapsulation:


 Encapsulation is used to reduce the complexity and improve reusability.
 Encapsulation defines the interface clearly which improves the readability and
understandability.
 Encapsulation helps to hide important data and ensures enhanced Security.
 The member variables and members are bundled into a single unit as a class which makes
the maintenance easy.
 The encapsulated classes are straightforward and are easy to manage and improves the
future development of the application.

Data Hiding Definition:


Data hiding is a technique especially practised in object-oriented programming (OOP).Data
hiding is hiding the details of internal data members of an object.
 Data hiding is also known as Information hiding.
 Sometimes Data Hiding includes Encapsulation. Thus Data Hiding is heavily related to
Abstraction and Encapsulation.
 Data Hiding is the one most important OOP mechanism. Which is hide the details of the
class from outside of the class.
 The Class used by only a limited set of variables and functions, others are hidden by the
class.
Example:
class Square
{
private:
int Num;
public:
void Get()
{
cout << "Enter Number:";
cin>>Num;
}
void Display()
{
cout << "Square Is:" << Num*Num;
}
};
void main()
{
Square Obj;

Page 39 of 99

Downloaded by Sri Suman ([email protected])


lOMoARcPSD|51487838

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.

Class and Objects


Class:
A class is an abstract data type that groups the data and its associated functions. It can
also hide the data and functions if required.
A class specification consists of two parts.
i. Declaration of a class and
ii. Definition of members functions and members variable of a class
The member scope and types are described by the class declaration. And the
implementation of member functions is described by the class function definition.
Syntax of Class declaration:
Class class-Name
{
Public / Private:
Member variable Declaration;
Public / Private:
Member Function Declaration;
}
The “class” keyword indicates an abstract data type called name of the class and body of
a class include member variable and member function declaration.
Example:
Class circle
{
Public:
int radius;
Page 40 of 99

Downloaded by Sri Suman ([email protected])


lOMoARcPSD|51487838

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

Downloaded by Sri Suman ([email protected])


lOMoARcPSD|51487838

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

Downloaded by Sri Suman ([email protected])


lOMoARcPSD|51487838

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.

Declaring of Object to a class:


The declaration of object to a class is similar with the declaration of variable to a data
types. The methods of defining the declared class object are known as class instantiations. For
every object, a separate memory is allocated. Memory allocation is done only for the member
functions of each class object. An object can be declared in two methods. They are as follows
Method1: an object can be declared as a normal variable.
Syntax:
Classname Objectname;
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”);
}

Page 43 of 99

Downloaded by Sri Suman ([email protected])


lOMoARcPSD|51487838

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

Downloaded by Sri Suman ([email protected])


lOMoARcPSD|51487838

CONSTRUCTORS and its TYPES


Constructors:
A constructor is a member function of a class which initializes objects of a class. In C++,
Constructor is automatically called when object(instance of class) create. It is special member
function of the class.
A constructor will have exact same name as the class and it does not have any return type
at all, not even void. Constructors can be very useful for setting initial values for certain member
variables.
A constructor is different from normal functions in following ways:
 Constructor has same name as the class itself
 Constructors don‟t have return type
 A constructor is automatically called when an object is created.
 If we do not specify a constructor, C++ compiler generates a default constructor for us
(expects no parameters and has an empty body).

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

Downloaded by Sri Suman ([email protected])


lOMoARcPSD|51487838

{
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

Downloaded by Sri Suman ([email protected])


lOMoARcPSD|51487838

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.
#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

Downloaded by Sri Suman ([email protected])


lOMoARcPSD|51487838

#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;
}
Output:
25
50
80
Garbage collection in C++
Dynamic allocation of object is done using new keyword. Sometimes allocation of new
objects fails due to insufficient memory. In such cases memory space consumed by unused
objects are deallocated and made available for reallocation. This is done manually in languages
such as C and C++ using delete keyword. In java new concept called garbage collection is
introduced fir this purpose. It is a trouble-tree approach which reclaims the objects automatically.
This is done without the interfering of the programmer. The objects which are not used for long
time and which does not have any references are identified and their space is deallocated. This
recycled space can now be used by other objects.
Garbage collection is only performed during program execution. It is a time consuming
process therefore it is performed only at relevant instance.

Dynamic Memory Allocation in C++


Dynamic memory allocation (i.e., allocation and release of memory) can be performed using
“New” and “Delete” operations.
“new” Operator:
The “new” operator is used to dynamically allocate the memory for objects which
return a pointer to its.

Page 48 of 99

Downloaded by Sri Suman ([email protected])


lOMoARcPSD|51487838

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.

Example of C++ Abstract class


#include<iostream.h>
#include<conio.h>
class BaseClass //Abstract class
{

public:
Page 49 of 99

Downloaded by Sri Suman ([email protected])


lOMoARcPSD|51487838

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()
{
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

Page 50 of 99

Downloaded by Sri Suman ([email protected])


lOMoARcPSD|51487838

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

Downloaded by Sri Suman ([email protected])


lOMoARcPSD|51487838

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

Downloaded by Sri Suman ([email protected])


lOMoARcPSD|51487838

}
// 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

Downloaded by Sri Suman ([email protected])


lOMoARcPSD|51487838

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.

The advantage of Operators overloading is to perform different operations on the same


operand.
Almost any operator can be overloaded in C++. However there are few operator which can
not be overloaded. Operator that are not overloaded are followsScope operator (::)
 Sizeof
 member selector(.)
 member pointer selector(*)
 ternary operator(?:)
Operator Overloading Syntax

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

Downloaded by Sri Suman ([email protected])


lOMoARcPSD|51487838

 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

Types of Operator Overloading


Operator Overloading can be done by using three approaches, they are
1. Overloading unary operator.
2. Overloading binary operator.
3. Overloading binary operator using a friend function.
Overloading Unary Operator: The unary operators operate on a single operand and following
are the examples of Unary operators
Page 55 of 99

Downloaded by Sri Suman ([email protected])


lOMoARcPSD|51487838

 The increment (++) and decrement (--) operators.


 The unary minus (-) operator.
 The logical not (!) operator.
The unary operators operate on the object for which they were called normally, this operator
appears on the left side of the object, like as !obj, -obj, and ++obj but sometime they can be used
as postfix as well like obj++ or obj--.
Following example explain how minus (-) operator can be overloaded for prefix as well as
postfix usage.
Example:
#include <iostream.h>
class Distance
{
private:
int feet;
int inches;
public:
Distance()
{
feet = 0;
inches = 0;
}
Distance(int f, int i)
{
feet = f;
inches = i;
}
void displayDistance()
{
cout << "F: " << feet << " I:" << inches <<endl;
}
Distance operator- ()
{
feet = -feet;
inches = -inches;
return Distance(feet, inches);
}
};
void main()
{
Distance D1(11, 10), D2(-5, 11);
-D1;
D1.displayDistance();
-D2;
D2.displayDistance();
}
Page 56 of 99

Downloaded by Sri Suman ([email protected])


lOMoARcPSD|51487838

OUTPUT:
F: -11 I:-10
F: 5 I:-11

2. Overloading Binary Operator: In binary operator overloading function, there should


be one argument to be passed. It is overloading of an operator operating on two operands.
The binary operators take two arguments and following are the examples of Binary operators.
we use binary operators very frequently like addition (+) operator, subtraction (-) operator
and division (/) operator.
Following example explains how addition (+) operator can be overloaded. Similar way, you
can overload subtraction (-) and division (/) operators.
Example:
#include <iostream.h>
class Box
{
Public:
double length;
double breadth;
double height;
public:
double getVolume(void)
{
return length * breadth * height;
}

void setLength( double len )


{
length = len;
}
void setBreadth( double bre )
{
breadth = bre;
}

Page 57 of 99

Downloaded by Sri Suman ([email protected])


lOMoARcPSD|51487838

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;
// Add two object as follows:
Box3 = Box1 + Box2;
Page 58 of 99

Downloaded by Sri Suman ([email protected])


lOMoARcPSD|51487838

// 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

Downloaded by Sri Suman ([email protected])


lOMoARcPSD|51487838

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

Downloaded by Sri Suman ([email protected])


lOMoARcPSD|51487838

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

Downloaded by Sri Suman ([email protected])


lOMoARcPSD|51487838

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

Downloaded by Sri Suman ([email protected])


lOMoARcPSD|51487838

Example of Multiple Inheritance:


#include <iostream.h>
class A
{
public:
A( )
{
cout<<"Constructor of A class"<<endl;
}
};
class B
{
public:
B( )
{
cout<<"Constructor of B class"<<endl;
}
};
class C: public A, public B
{
public:
C( )
{
cout<<"Constructor of C class"<<endl;
}
};
void main( )
{
C obj; //Creating object of class C

}
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

Downloaded by Sri Suman ([email protected])


lOMoARcPSD|51487838

Example of Multilevel inheritance:


#include <iostream.h>
class A
{
public:
A( )
{
cout<<"Constructor of A class"<<endl;
}
};
class B: public A
{
public:
B( )
{
cout<<"Constructor of B class"<<endl;
}
};
class C: public B
{
public:
C( )
{
cout<<"Constructor of C class"<<endl;
}
};
void main( )
{
C obj; //Creating object of class C

}
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

Downloaded by Sri Suman ([email protected])


lOMoARcPSD|51487838

Example of Hierarchical inheritance:


#include <iostream.h>
class A
{
public:
A( )
{
cout<<"Constructor of A class"<<endl;
}
};
class B: public A
{
public:
B( )
{
cout<<"Constructor of B class"<<endl;
}
};
class C: public A
{
public:
C( )
{
cout<<"Constructor of C class"<<endl;
}
};
void main( )
{
C obj; //Creating object of class C
B obj1; //Creating object of class B
}
Output:
Constructor of A class
Constructor of C class
Constructor of A class
Constructor of B class
Page 65 of 99

Downloaded by Sri Suman ([email protected])


lOMoARcPSD|51487838

5. Hybrid (Virtual) Inheritance: Hybrid Inheritance is implemented by combining more


than one type of inheritance. For example: Combining Hierarchical inheritance and Multiple
Inheritance. Below image shows the combination of hierarchical and multiple inheritance:

Visibility mode or Access Modifiers or Access Specifiers


C++ access specifiers are used for determining or setting the boundary for the availability of
class members (data members and member functions) beyond that class.
For example, the class members are grouped into sections, private protected and public.
These keywords are called access specifiers which define the accessibility or visibility level of
class members. Access specifiers are divided into 3 types. They are
1. private access specifier
2. protected access specifier
3. public access specifier
1. Private access specifier:
The class members declared as private can be accessed only by the functions inside the
class. They are not allowed to be accessed directly by any object or function outside the class.
Only the member functions or the friend functions are allowed to access the private data
members of a class.

2. Public access specifier:


All the class members declared under public will be available to everyone. The data
members and member functions declared public can be accessed by other classes too. The public
members of a class can be accessed from anywhere in the program using the direct member
access operator (.) with the object of that class.
3. Protected access specifier:
Protected access modifier is similar to that of private access modifiers, the difference is
that the class member declared as Protected are inaccessible outside the class but they can be
accessed by any subclass(derived class) of that class.

Page 66 of 99

Downloaded by Sri Suman ([email protected])


lOMoARcPSD|51487838

Accessibility in Public Inheritance


Accessibility private variables protected variables public variables
Accessible from own class? yes yes yes
Accessible from derived class? no yes yes
Accessible from 2nd derived class? no yes yes

Accessibility in Protected Inheritance


private
Accessibility protected variables public variables
variables
Accessible from own class? yes yes yes
yes
Accessible from derived class? no yes (inherited as protected
variables)
Accessible from 2nd derived
no yes yes
class?

Accessibility in Private Inheritance


private
Accessibility protected variables public variables
variables
Accessible from own class? yes yes yes
yes yes
Accessible from derived
no (inherited as private (inherited as private
class?
variables) variables)
Accessible from 2nd derived
no no no
class?
Page 67 of 99

Downloaded by Sri Suman ([email protected])


lOMoARcPSD|51487838

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();
};

class typist: public staff


{
private:
int speed;
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

Downloaded by Sri Suman ([email protected])


lOMoARcPSD|51487838

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

Multilevel Inheritance program:


#include <iostream.h>
class base //single base class
{
public:
int x;
void getdata()
{
cout << "Enter value of x= "; cin >> x;
}
Page 69 of 99

Downloaded by Sri Suman ([email protected])


lOMoARcPSD|51487838

};
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

Downloaded by Sri Suman ([email protected])


lOMoARcPSD|51487838

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

Enter value of x and y:


2
3
Product= 6
Enter value of x and y:
2
3
Sum= 5

Multiple Inheritance Program


#include<iostream.h>

Page 71 of 99

Downloaded by Sri Suman ([email protected])


lOMoARcPSD|51487838

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

Downloaded by Sri Suman ([email protected])


lOMoARcPSD|51487838

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

Downloaded by Sri Suman ([email protected])


lOMoARcPSD|51487838

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.

Virtual Class or Virtual Base Class :


If more than one sub classes are derived from a single Base class is made virtual. This
is done at avoid the duplication of the member variables of that class. Only a single copy of the
members can be used by the subclasses. A class can be made virtual by just placing the keyword
“virtual” before class name. The virtual classes are mostly used in the concept of multipath
inheritance (Hierarchical inheritance and multilevel inheritance).
Virtual base class is a class in which virtual keyword is placed before the name of the
class while it is inherited. Following example explain the syntax for declaring virtual base
classes.
Syntax:
Class X
{
Public:
int x;
};
Class Y : virtual public X
{
Public:
int y;
};
Class Z : virtual public X
{
Public:
int z;
};
Class M : public Y,Z
{

Page 74 of 99

Downloaded by Sri Suman ([email protected])


lOMoARcPSD|51487838

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

Downloaded by Sri Suman ([email protected])


lOMoARcPSD|51487838

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

Downloaded by Sri Suman ([email protected])


lOMoARcPSD|51487838

}
};
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

Advantages of virtual functions:


1. Runtime Polymorphism can succeed.
2. The members of the derived class can be accessed.
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.

Page 77 of 99

Downloaded by Sri Suman ([email protected])


lOMoARcPSD|51487838

PURE VIRTUAL FUNCTION


A pure virtual function is a virtual function in C++ for which we need not to write any
function definition and only we have to declare it. It is declared by assigning 0 in the declaration.
A virtual function will become pure virtual function when you append "=0" at the end of
declaration of virtual function. Pure virtual function doesn't have body or implementation. We
must implement all pure virtual functions in derived class. Pure virtual function is also known as
abstract function. A class with at least one pure virtual function or abstract function is called
abstract class. We can't create an object of abstract class. Member functions of abstract class will
be invoked by derived class object.
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
C++ Stream Classes
In C++ there are number of stream classes for defining various streams related with files
and for doing input-output operations. All these classes are defined in the file iostream.h. Figure
given below shows the hierarchy of these classes.

Page 78 of 99

Downloaded by Sri Suman ([email protected])


lOMoARcPSD|51487838

 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

Downloaded by Sri Suman ([email protected])


lOMoARcPSD|51487838

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.

C++ Console I/O functions


C++ language provides us console input/output functions. As the name says, the console input/output
functions allow us to -
 Read the input from the keyboard, entered by the user at the console.
 Display the output to the user at the console.
There are two kinds of console input/output functions :

No. Functions

1 Formatted input/output functions.

2 Unformatted input/output functions.

C++ Formatted I/O Functions


Formatted console input/output functions are used for performing input/output operations
at console and the resulting data is formatted and transformed.
Some of the most important formatted console input/output functions are –

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

Downloaded by Sri Suman ([email protected])


lOMoARcPSD|51487838

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 -

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

Downloaded by Sri Suman ([email protected])


lOMoARcPSD|51487838

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

Downloaded by Sri Suman ([email protected])


lOMoARcPSD|51487838

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

Downloaded by Sri Suman ([email protected])


lOMoARcPSD|51487838

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

Downloaded by Sri Suman ([email protected])


lOMoARcPSD|51487838

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

Downloaded by Sri Suman ([email protected])


lOMoARcPSD|51487838

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

Downloaded by Sri Suman ([email protected])


lOMoARcPSD|51487838

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

Downloaded by Sri Suman ([email protected])


lOMoARcPSD|51487838

Reasons for Run-time Errors Occurrence:


i. Division-by zero condition
ii. Exceeding the bounds of an array
iii. Running out of memory
iv. Object initialization to an impossible value.
Example:
#include<iostream.h>
Void main( )
{
int a=10,b=0,c;
c=a/b;
cout<<”c values is”<<c;
}
The above program saves as “division.cpp”. after saving we compile it. In compiling, there are
any no errors. That means compiling is successfully. After than we can run it program. But in run the
program, the program to display the error. That is “cannot divisible by zero”

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

Downloaded by Sri Suman ([email protected])


lOMoARcPSD|51487838

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

Downloaded by Sri Suman ([email protected])


lOMoARcPSD|51487838

Exception with Arguments:


Exception handler is responsible for handling exceptional situations that occur in the
program. In order to catch the exceptions the related code must be placed in try block with this
the exception will be thrown in exception conditions. The control will be transferred to the
exception handler.
The throw exception is capable of accepting a parameter that is passed as arguments to
exception handler. An exception handler can be declared using catch keyword which contains at
least one parameter. The type of argument in catch statement should be same as that parameter
used in throw statement. Otherwise the exception will not be caught. To avoid multi[le exception
handlers can be used. The different catch statements are used which in turn make use of different
parameter types.
Example:
#include<iostream.h>
#include<string.h>
Void main( )
{
int a,b,c;
cout<<”enter the a,b values”;
cin>>a>>b;
try
{
if(b==0)
{
throw b;
}
if(b<0)
{
throw “negative denominator not allowed”;
}
c=a/b;
cout<<”the value of C is :”<<c
}
catch(int num)
{
Cout<<”we canot enter”<<num<<:in denominator”;
}
}

Page 90 of 99

Downloaded by Sri Suman ([email protected])


lOMoARcPSD|51487838

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

Downloaded by Sri Suman ([email protected])


lOMoARcPSD|51487838

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

Downloaded by Sri Suman ([email protected])


lOMoARcPSD|51487838

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

Downloaded by Sri Suman ([email protected])


lOMoARcPSD|51487838

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

Downloaded by Sri Suman ([email protected])


lOMoARcPSD|51487838

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

Downloaded by Sri Suman ([email protected])


lOMoARcPSD|51487838

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

Downloaded by Sri Suman ([email protected])


lOMoARcPSD|51487838

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.

Linked List Data Structure In C++


A linked list is a linear dynamic data structure to store data items. We have already seen
arrays in our previous topics on basic C++. We also know that arrays are a linear data structure
that store data items in contiguous locations. Unlike arrays, the linked list does not store data
items in contiguous memory locations. A linked list consists of items called “Nodes” which
contain two parts. The first part stores the actual data and the second part has a pointer that points
to the next node. This structure is usually called “Singly linked list”.
The following diagram shows the structure of a singly linked list.

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

Downloaded by Sri Suman ([email protected])


lOMoARcPSD|51487838

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.

Thus the new linked list becomes 1->2->4->6->8->10.


#2) After the given Node
Here, a node is given and we have to add a new node after the given node. In the below-linked
list a->b->c->d ->e, if we want to add a node f after node c then the linked list will look as
follows:

Page 98 of 99

Downloaded by Sri Suman ([email protected])


lOMoARcPSD|51487838

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

Downloaded by Sri Suman ([email protected])

You might also like