Sie sind auf Seite 1von 221

OBJECT ORIENTED PROGRAMMING WITH C++

(EID201)

Course File

GITAM UNIVERSITY
HYDERABAD CAMPUS

PREPARED BY
D.SRINIVASA RAO
ASSISTANT PROFESSOR
DEPARTMENT OF IT
2

CONTENTS
S.No Topic Page no.
1 Syllabus 1-2
2 Module-1 3-54
3 Module-2 55-100
4 Module-3 101-130
5 Module-4 131-181
6 Module-5 182-217
7 Previous modelpaper-1 218-219
1

EID201 : OBJECT ORIENTED PROGRAMMING WITH C++


Module I
Introduction to OOP: Procedure oriented programming, object
oriented programming, basic concepts of OOP, benefits and
applications of OOP, simple C++ program, namespace scope, structure
of C++ Program, creating, compiling and linking a file.
Tokens : Keywords, identifiers, constants, basic data types, user
defined data types, storage classes, derived data types, dynamic
initialization of variables, reference variables, operators in C++, scope
resolution operator, member dereferencing operators, memory
management operators.

Module II
Control Structures.
Classes and Objects: Specifying a class, defining member functions,
C++ program with class, private member functions, arrays within
class, memory allocation for objects, static data members, static
member functions, arrays of objects, returning objects.
Functions in C++: main function, function prototyping, call by
reference, return by reference, inline functions, default arguments.

Module III
More about Functions: Function overloading, friendly functions: friend
function, a function friendly to two classes, objects as function
arguments.
Constructors & Destructors: Constructors, parameterized
constructors, multiple constructors in a class, constructors with
default arguments, copy constructors, dynamic constructors,
destructors.
2

Module IV

Inheritance: Introduction to inheritance, single inheritance, making a


private member inheritable (protected member), multi-level
inheritance, multiple inheritance, hierarchical inheritance, hybrid
inheritance.
Operator Overloading: Rules for overloading operators, overloading
unary operators, overloading binary operators.
Pointers: Introduction to pointers, declaring and initializing pointers,
arithmetic operations on pointers, pointers with arrays, arrays of
pointers, pointers to objects, 'this' pointer.

Module V
Polymorphism and Virtual Functions: Compile-time polymorphism,
runtime polymorphism, virtual functions.
Managing Console I/O Operations: Unformatted I/O operations,
formatted console i/o operations (width( ), precision( ), fill( )),
managing output with manipulators (setw( ), endl).
Templates: Introduction, function templates, class templates.
Exception Handling: Introduction, exception handling mechanism,
throwing mechanism, catching mechanism.

Text Book(s)
1. E. Balagurusamy, Object Oriented Programming with C++, 6/e,
McGraw Hill, 2013.
References
1. Sourav Sahay, Object Oriented Programming with C++, 2/e, Oxford
University Press, 2012.
2. Behrouz A. Forouzan and Richard F. Gilberg, Computer Science : A
Structured Approach Using C++, 2/e, Cengage Learning, 2003.
3. Ashok N. Kamthane, Object Oriented Programming with ANSI and
Turbo C++, 1/e, Pearson Education, 2006.
3

EID201: OBJECT ORIENTED PROGRAMMING WITH C++


Module I
Introduction to OOP: Procedure oriented programming, object
oriented programming, basic concepts of OOP, benefits and
applications of OOP, simple C++ program, namespace scope, structure
of C++ Program, creating, compiling and linking a file.

Tokens : Keywords, identifiers, constants, basic data types, user


defined data types, storage classes, derived data types, dynamic
initialization of variables, reference variables, operators in C++, scope
resolution operator, member dereferencing operators, memory
management operators.
4

1. Procedure oriented programming

• In the procedure oriented approach, the problem is viewed as


the sequence of things to be done such as reading, calculating
and printing such as Cobol, Fortran and C.
• The primary focus is on functions.
• The technique of hierarchical decomposition has been used to
specify the tasks to be completed for solving a problem.


Procedure oriented programming basically consists of writing a
list of instructions for the computer to follow, and organizing
these instructions into groups known as functions.
• We normally use flowcharts to organize these actions and
represent the flow of control from one action to another.
• In a multi-function program, many important data items are
placed as global so that they may be accessed by all the
functions.
• Each function may have its own local data.
• Global data are more vulnerable to an inadvertent change by a
function.
• In a large program, it is very difficult to identify what data is
used by which function.
• In case we need to revise an external data structure, we also
need to revise all functions that access the data.
• This provides an opportunity for bugs to creep in.
• Another serious drawback with the procedural approach is that
we do not model real world problems very well.
• This is because functions are action-oriented and do not really
corresponding to the element of the problem.
Some Characteristics exhibited by procedure-oriented
programming are:
Emphasis is on doing things (algorithms).
• Large programs are divided into smaller programs known as
functions.
• Most of the functions share global data.
• Data move openly around the system from function to function.
• Employs top-down approach in program design.
5

2. Object Oriented Programming

• The major motivating factor in the invention of object-oriented


approach is to remove some of the flaws encountered in the
procedural approach
• OOP treats data as a critical element in the program
development and does not allow it to flow freely around the
system.
• It ties data more closely to the function that operate on it, and
protects it from accidental modification from outside function.
• OOP allows decomposition of a problem into a number of
entities called objects and then builds data and function
around these objects.
• The data of an object can be accessed only by the function
associated with that object.
• However, function of one object can access the function of other
objects.

Some of the features of object oriented programming are:

• Emphasis is on data rather than procedure.


• Programs are divided into what are known as objects.
• Data structures are designed such that they characterize the
objects.
• Functions that operate on the data of an object are ties together
in the data structure.
• Data is hidden and cannot be accessed by external function.
6

• Objects may communicate with each other through function.


• New data and functions can be easily added whenever
necessary.
• Follows bottom up approach in program design.

Difference between procedure oriented and objected oriented

Subject of Procedure Oriented Object Oriented


Difference Programming (POP) Programming (OOP)

Decompose the main problem Decompose the main


Problem
in small parts called functions. problem in small parts
decomposition
called objects.

Connects small parts of the Connects small parts of


Connections of
program by passing parameters the program by passing
parts
& using operating system. messages.

Emphasizing Emphasizes on functions. Emphasizes on data.

In large programs, most Each object controls


Use of data
functions use global data. data under it.

Data may get passed from one Data never get passed
Passing of data function to another. from one object to
another.

Appropriate & effective Data stay secured as


techniques are unavailable to no external function
Security of data
secure the data. can use data of an
object.

Modification of a completed Modifications are easy


Modification of program is very difficult and it as objects stay
program may affect the whole program. independent to declare
and define.

Designing Employs top-down approach for Employs bottom-up


approach designing programs. approach for designing.

Data In large programs, it is very As data and functions


7

identification difficult to find what data has stay close, it is easy to


been used by which function. identify data.

Languages like C, FORTRAN, Languages like C++,


Used languages
COBOL etc. use POP. JAVA etc. use OOP.

No. C C++

1) C follows the procedural style C++ is multi-paradigm. It


programming. supports both procedural and
object oriented.

2) Data is less secured in C. In C++, you can use modifiers


for class members to make it
inaccessible for outside users.

3) C follows the top-down C++ follows the bottom-up


approach. approach.

4) C does not support function C++ supports function


overloading. overloading.

5) In C, you can't use functions in In C++, you can use functions


structure. in structure.

6) C does not support reference C++ supports reference


variables. variables.

7) In C, scanf() and printf() are C++ mainly uses stream cin


mainly used for input/output. and cout to perform input and
output operations.

8) Operator overloading is not Operator overloading is


possible in C. possible in C++.

9) C programs are divided C++ programs are divided


into procedures and modules into functions and classes.

10) C does not provide the feature of C++ supports the feature of
namespace. namespace.
8

11) Exception handling is not easy in C++ provides exception


C. It has to perform using other handling using Try and Catch
functions. block.

3. Basic concepts of OOPs

1. Classes
2. Objects
3. Data abstraction
4. Data encapsulation
5. Inheritance
6. Polymorphism
7. Dynamic Binding
8. Message Passing

Classes:
• The entire set of data and code of an object can be made a user-
defined data type with the help of a class. Objects are actually
variable of the type class.
• Once a class has been defined, we can create any number of
objects belonging to that class. Thus, a class is collection of
objects of similar type.
• Classes are user defined data types and behaves like the built-
in type of a programming language.
9

Objects:

• bjects are the basic run-time entities in an object-oriented


system.
• They may represent a person, a place a bank account, a table of
data or any item that the program has to handle.
• Programming problem is analyzed in terms of objects and the
nature of communication between them.
• Objects take up space in the memory & have an associated
address like structure in c.
• When a program executes, the object interacts by sending
messages to one another.
• Ex. If there are two objects "customer" and "account" then the
customer object may send a message to account object requesting
for the bank balance. Thus each object contains data, and code to
manipulate the data.

#include <iostream>
using namespace std;
class Student
{
public:
int id;//data member (also instance variable)
string name;//data member(also instance variable)
};
int main()
{
Student s1; //creating an object of Student
s1.id = 201;
s1.name = "surya maggi";
cout<<s1.id<<endl;
cout<<s1.name<<endl;
return 0;
}

OUTPUT:
201
surya maggi
10

Data Abstraction :
• Abstraction refers to the act of representing essential features
without including the background details or explanation.
• Classes use the concept of abstraction and are defined as a list of
abstract attributes such as size, wait, and cost, and function operate
on these attributes.
• They encapsulate all the essential properties of the object that are to
be created.
• The attributes are some time called data members because they hold
information. The functions that operate on these data are sometimes
called methods or member function.

Data encapsulation :
• The wrapping up of data and functions into a single unit called
class is known as encapsulation.
• The data is not accessible to the outside world, and only those
functions which are wrapped in the class can access it.
• These functions provide the interface between the objects data and
the program. This insulation of the data from direct access by the
program is called data hiding or information hiding

Inheritance :
• Inheritance is the process by which object of one class acquire the
properties of objects of another class.
• In OOPs, the concept of inheritance provides 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 wil1 have combined features of both the classes.
11

Polymorphism :
• Polymorphism is important oops concept. It means ability to take
more than one form.
• In polymorphism an operation may shows different behavior in
different instances. The behavior depends upon the type of data
used in the operation.
• For Ex- Operation of addition for two numbers, will generate a sum.
If the operands are strings, then the operation would produce a
third string by concatenation.
• The process of making an operator to show different behavior in
different instance is called as operator overloading.
• C++ support operator overloading.

EX:

Fig illustrates that a single function name can be used to handle


different number and different types of argument. This is something
similar to a particular word having several different meanings
depending upon the context. Using a single function name to perform
different type of task is known as function overloading.
12

Dynamic Binding :
• Binding refers to the linking of a procedure call to the code to be
executed in response to the call.
• Dynamic binding means that the code associated with a given
procedure call is not known until the time of the call at run
time.
• It is associated with polymorphism and inheritance.
• A function call associated with a polymorphic reference depends on
the dynamic type of that reference.
• Consider the procedure “draw” in fig. by inheritance, every object
will have this procedure. Its algorithm is, however, unique to each
object and so the draw procedure will be redefined in each class
that defines the object. At run-time, the code matching the object
under current reference will be called.

Message Passing :
• An object-oriented program consists of a set of objects that
communicate with each other.
• The process of programming in an object-oriented language, involves
the following basic steps:
✓ Creating classes that define object and their behaviour
✓ Creating objects from class definitions, and
✓ Establishing communication among objects.
• Objects communicate with one another by sending and receiving
information much the same way as people pass messages to one
another.
• The concept of message passing makes it easier to talk about building
systems that directly model or simulate their real-world
counterparts.
• A Message for an object is a request for execution of a procedure, and
therefore will invoke a function (procedure) in the receiving object
that generates the desired results.
13

• Message passing involves specifying the name of object, the name of


the function (message) and the information to be sent.
• Employee. Salary (name);
• Employee-object, Salary-message, name-Information

4. Benefits & Applications of OOPs

1. Reusability:

In OOP‘s programs functions and modules that are written by a user


can be reused by other users without any modification.

2. Inheritance:

Through this we can eliminate redundant code and extend the use
of existing classes.

3. Data Hiding:

The programmer can hide the data and functions in a class from other
classes. It helps the programmer to build the secure programs.

4. Reduced complexity of a problem:

The given problem can be viewed as a collection of different objects.


Each object is responsible for a specific task. The problem is solved
by interfacing the objects. This technique reduces the complexity of
the program design.

5. Easy to Maintain and Upgrade:

OOP makes it easy to maintain and modify existing code as new


objects can be created with small differences to existing ones.

6. Message Passing:

The technique of message communication between objects makes the


interface with external systems easier.
14

7. Modifiability:

It is easy to make minor changes in the data representation or the


procedures in an OO program. Changes inside a class do not affect
any other part of a program, since the only public interface that the
external world has to a class is through the use of methods.

Applications of OOP:

1. Real time Systems: -

A real-time system is a system that give output at given instant and


its parameters changes at every time. A real-time system is nothing
but a dynamic system. Dynamic means the system that changes every
moment based on input to the system. OOP approach is very useful
for Real time system because code changing is very easy in OOP
system and it leads toward dynamic behaviour of OOP codes thus
more suitable to real time system.

2. Simulation and Modelling: -

System modelling is another area where criteria for OOP approach is


countable. Representing a system is very easy in OOP approach
because OOP codes are very easy to understand and thus is preferred
to represent a system in simpler form.

3. Hypertext and Hypermedia: -

Hypertext and hypermedia is another area where OOP approach is


spreading its legs. Its ease of using OOP codes that makes it suitable
for various media approaches.

4. Decision support system: -

Decision support system is an example of Real time system that too


very advance and complex system. More details are explained in real
time system.
15

5. CAM/CAE/CAD System: -

Computer has wide use of OOP approach. This is due to time saving
in writing OOP codes and dynamic behaviour of OOP codes.

6. Office Automation System: -

Automation system is just a part or type of real time system.


Embedded systems make it easy to use OOP for automated system.

7. AI and expert system: -

It is mixed system having both hypermedia and real-time system.

5. Structure of C++

• Documentation Section

• Preprocessor Directives or Compiler Directives Section

✓ Link Section
✓ Definition Section
• Global Declaration Section

• Class declaration or definition

• Main C++ program function called main ( )

• Beginning of the program: Left brace {

• Object declaration part;

• Accessing member functions (using dot operator);

• End of the main program: Right brace}

Documentation Section

In Documentation section we give the Heading and Comments.


Comment statement is the non-executable statement. Comment can
be given in two ways:
16

(i) Single Line Comment: Comment can be given in single line by


using "//".

The general syntax is: //Single Text line

For Example: //Add Two Numbers (Heading of the program)

C= a + b; //Store the value of a + b in C.(Comment to explain given


statement)

(ii) Multiple Line Comment: Comment can be given in multiple


lines starting by using "/*" and end with "*/".

The general syntax is:

/* Text Line 1

Text Line 2

Text Line 3 */

For Example: /* Write a C++ program to find the sum and average of
five numbers. */

Preprocessor Directives

• These are compiler preprocessor statements.


• These are also optional statements, but becomes compulsory if your
compiler has INCLUDE and LIB subdirectories in the specified drive
TCPLUS or having any name.
• Pre-compiler statements are divided into two parts.

(i) Link Section:

In the Link Section, we can link the compiler function like

cout<<, cin>>, sqrt ( ), fmod ( ), sleep ( ), clrscr ( ), exitO, strcatO etc.


with the INCLUDE subdirectory having header files like iostream.h,
conio.h, math.h, dos.h, string.h, ctype.h, process.h etc.

It becomes very useful during the compilation and the linkage phase.
17

The general syntax is:

#include <header file> .

or

#include "header file"

For example:

#include <iostream.h>

#include <conio.h>

#include "dos.h"

ii) Definition Section:

The second section is the Definition section by using which we can


define a variable with its value. For this purpose define statement is
used.

The general syntax is:

#define variable_name value

For example:

#define PI 3.142

#define A 100

#define NAME "Dinesh"

Global Declaration Section

• In this section, we declare some variables before starting of the


main program or outside the main program.
• These variables are globally declared and used by the main
function or sub function.
• These variables are called global variables.
• In some programs we use function sub-programs.
18

• So we declare some variables in the main program and function


sub program having common name.
• This creates the duplicity or redundancy in defining the
variables.
• So we can take the common variable declaration above the main
program, which is also called global variable declaration.
• The global variables are automatically initialized with zero,
hence there is no chance of garbage value. The global variable
declaration can be done by the statement given below.

The general syntax is:

data type vl,v2,v3………. vn;


Here data types are int, float, char, double etc.
vl,v2,v3, .... vn is the list of global variables(v).
For example:

Following are the some valid global declaration statements


int a, b, c;
float x,y,z;
char ch, name[10], address[20];

6. Namespace scope

• A namespace defines an area of code in which all identifiers are


guaranteed to be unique.
• By default, all variables and functions are defined in the global
namespace.
• A namespace is a region of declaration.
• The purpose of namespace is to avoid collision of identifiers (i.e.
to avoid collision of variables or class names or function names
etc.).
• Elements declared in one namespace are different from those
declared in another.
19

• In order to help avoid issues where two independent pieces of


code have naming collisions with each other when used
together, C++ allows us to declare our own namespaces via the
namespace keyword.
• Anything declared inside a user-defined namespace belongs to
that namespace, not the global namespace.
• One of the new features added to this language is namespace.
• A namespace permits grouping of various entities like classes,
objects, functions and various C++ tokens, etc., under a single
name.
• Different users can create separate namespaces and thus can
use similar names of the entities.
• This avoids compile time error that may exist due to identical-
name conflicts.
• The C++ Standards Committee has rearranged the entities of
the standard library under a namespace called std.
• In Example, the statement using namespace std informs the
compiler to include all the entities present in the namespace
std.
• The entities of a namespace can be accessed in different ways
which are listed here.

• By specifying the using directive

using namespace std;

cout<<"Hello World";

• By specifying the full member name std: :cout<<"Hello World";

• By specifying the using declaration using std:: cout;

cout<<"Hello World";

• As soon as the new-style header is included, its contents are


included in the std namespace.
• Thus, all the modern C++ compilers support these statements.
20

#include<iostream>
using namespace std;
Some old compilers may not support these statements.

In that case, the statements are replaced by this single statement.

#include<iostream.h>

7. Creating, Compiling and Linking a file

Creating a c++ file:

1. Open the terminal (Alt + Ctrl +t)-gedit filename.C


2. Write c++ program
3. Execute program== CC filename.C
Compilation

• This phase translates the program into a low-level assembly


level code.
• The compiler takes the pre-processed file (without any
directives) and generates an object file containing assembly level
code.
• Now, the object file created is in the binary form.
• In the object file created, each line describes one low level
machine level instruction.
• The conversion to assembly language is important as it is
common output language for many compilers of different high-
level languages.
• There is also assembly phase which converts these object files
in assembly code into machine level instructions and the file
created is a relocatable object code.
• Hence, the compilation phase generates the relocatable object
program and this program can be used in different places
without have to compile again.
21

• But we still can’t run these object files until to convert them into
executable file, now here linker comes into play, which links all
the object files to generate single executable file.
Example: CC file1.C

Linking

• Linking as the name suggests, refers to creation of a single


executable file from multiple object files.
• The file created after linking is ready to be loaded into memory
and executed by the system.
• There is difference in linking and compilation when it comes to
understanding errors.
• Compiler shows errors in syntax, for example semi-colon not
mentioned, data type not defined etc but if there is an error that
function has been defined multiple times, then this error is from
linker as its indicating that two or more source code files have
the same meaning and that is leading to an error.
22

8. Simple C++ program

Write a C++ program to find the area of circle using basic


structure of C++ program with c1asses.

1. Documentation Section: Use single line comment

// Program to find the area of circle using basic structure of C++


program

2. Preprocessor Directives: Link and Definition Section

#include <iostream> II Link Section using namespace std;

#define PI 3.142 II Definition Section

3. Global Declaration Section

float r;

4. Class declaration or definition

class Circle // Class definition (Circle class is created)


{
private:
float area; // Data member public:
void read( ) // Member function
{
cout<<"Enter the radius of the circle:";
cin>>r;
}
void display( )
{
area = PI * r*r;
cout<< "Area of circle is " <<area;
}
};
23

5. //Main program starts from main() function


6. //Beginning of the main program: Left brace
main()
{
Circle c1;
c1.read( );
c1.display( );
//7. Ending of the main program: Right brace
}
24

9 TOKENS

KEYWORDS:

• Every word in C++ language is a keyword or an identifier.


• Keywords in C++ language cannot be used as a variable name.
• They are specifically used by the compiler for its own purpose
and they serve as building blocks of a C++ program.
• C++ language has some reserve words which are called
keywords of C++ language.
• These are the part of the C++ Tokens.
• There are 63 keywords currently defined for Standard C++.
• Together with the formal C++ syntax, they form the C++
programming language.

Table : C++ Keywords

Asm Auto bool break case

catch Char class const_cast continue

default delete do double else

enum dynamic_cast extern false float

For union unsigned using friend

goto If inline int long

mutable virtual namespace new operator

private protected public register void

reinterpret_cast return short signed sizeof

static static_cast volatile struct switch

template This throw true try

typedef typeid unsigned wchar_t while


25

Constants in C++:
• Constants refer to fixed values that the program may not alter.
• Constants can be of any of the basic data types.
• The way each constant is represented depends upon its type.
• Constants are also called literals.
• C++ has two kinds of constants: literal, and symbolic.

Definition: "A constant value is the one which does not change
during the execution of a program."

• Constant uses the secondary storage area.


• Constants are those quantities whose value does not vary
during the execution of the program i.e. constant has fixed
value.
• Constants in every language are the same.

• For example, in the C++ language some valid constant are:

53.7 , -44.4, +83.65, "Dinesh", 'M', "2013" etc.

In C++ language constants are of two types:


1. Numeric Constant
2. Non-Numeric Constant (Character Constant)

These are further sub-divided into more


categories.

Numeric Constant

✓ These have numeric value having combination of sequence of


digits i.e. from 0-9 as alone digit or combination of 0-9 with or
without decimal point (precision value) having positive or
negative sign.
✓ These are further sub-divided into two categories as:
(i) Integer Numeric Constant
(ii) Float or Real Numeric Constant

(i) Integer Numeric Constant

✓ An Integer Numeric Constant is a sequence of digits


(combination of 0-9 digits without any decimal point or without
precision), optionally preceded by a plus or minus sign.
26

There are 3 types of integer numeric constant namely decimal integer,


octal integers and hexadecimal integer.
(a) Decimal Integer Numeric Constant: These have no decimal point
in it and are either be alone or be the combination of 0-9 digits. These
have either +ve or -ve sign. For example: 1214, -1321, 10,254, -78,
+99 etc.
(b) Octal Integer Numeric Constant: These consist of combination of
digits from 0-7 with positive or negative sign. It has leading with 0 or 0
(upper or lower case) means Octal or octal. For example: 0317,003,
045 etc.
(c) Hexadecimal Integer Numeric Constant: These have hexadecimal
data. It has leading ox, OX, Ox or x, X. These have combination of 0-9
and A-F (a-f) or alone. The letters a-f or A-F represents the numbers
10-15. For example: 0x232, 0x92, 0xACD, 0xAEF etc.

(ii) Float or Real Numeric Constant

✓ Float Numeric Constants consists of a fractional part in their


representation;
✓ Integer constants are inadequate to represent quantities that
vary continuously.
✓ These quantities are represented by numbers containing
fractional parts like 26.082.
Examples of real constants are:
0.0026, -0.97, 435.29, +487.0, 3.4E-2, 4.5E5
✓ A floating-point constant consists of a sequence of decimal
digits, a decimal point, and another sequence of decimal digits.
✓ A minus sign can precede the value to denote a negative value.
✓ Either the sequence of digits before the decimal point or after
the decimal point can be omitted, but not both.
Float Numeric constants are further divided into two parts.
One is Mantissa Part and the other is Exponent Part.
(a) Mantissa part: The part without E and having a decimal point
is called Mantissa Real part
e.g. 45.5, 22.43, 0.5 etc. it is also called without exponent part.
(b) Exponent part:
✓ The exponent part has an E within it.
✓ It is also called a scientific notation.
27

✓ Here E has base value 10. it computes the power.


✓ For example: 4.2xl02 can be written as 4.2E2, 4.2xlO-5 can be
written as 4.2E- 5.
✓ Similarly some more valid real numeric constant are as: 54.73 E
-4,51.9 E +11 etc.
Character Constant
✓ Character constants have either a single character or group of
characters or a character with backslash used for special
purpose.

✓ These are further subdivided into three types:


(i) Single Character Constant
(ii) String Character Constant
(iii) Backslash Character Constant

(i) Single Character Constant

➢ Single Character constants are enclosed between single


quotes(').
➢ For example, 'a' and '%' are both character constants.
➢ So these are also called single quote character constant.
For example: 'a', 'M', '5', '+', '1' etc. are some valid single character
constant.

(ii) String Character Constant

➢ C++ supports another type of constant: the string.


➢ A string is a set of characters enclosed in double quotes (").
➢ For example: "Punar Deep" is a string.
➢ We must not confuse strings with characters.
➢ A single character constant is enclosed in single quotes, as in
'a'. However, "a" is a string containing only one letter.
For example:
✓ "Dinesh", "Hello", "2013", "2013-2020", "5+3", "?+!" etc. are some
valid string character constant.
✓ These are used for printing purpose or display purpose in the
C++ program's output statements.
✓ These can also be used for assigning the string data to the
character (string) type variables.
28

(iii) Backslash Character Constants

✓ Enclosing character constants in single quotes works for most


printing characters.
✓ A few, however, such as the carriage return, can't be.
✓ For this reason, C++ includes the special backslash character
constants, shown below, so that you may easily enter these
special characters as constants.
✓ These are also referred to as escape sequences.
✓ We should use the backslash codes instead of their ASCII
equivalents to help ensure portability.
✓ These are used for special purpose in the C++ language.
✓ These are used in output statements like cout etc.

Escape Sequences
A list of backslash character constant or escape sequence is as in the
below table:

Symbolic constants
We can use the #define preprocessor directive in order to declare a
symbolic constant:
#define DOLLAR 122
int nYen = nDollars *
DOLLAR;
29

There are two major problems with symbolic constants declared using
#define.
o First, because they are resolved by the preprocessor, which
replaces the symbolic name with the defined value, #defined
symbolic constants do not show up in the debugger. Thus, if
you only saw the statement int nYen = nDollars * DOLLAR;, you
would have to go looking for the #define declaration in order to
find out what value of DOLLAR was used.

o Second, #defined values always have global scope. This means


a value #defined in one piece of code may have a naming
conflict with a value #defined with the same name in another
piece of code.

A better way to do symbolic constants is through use of the const


keyword. Const variables must be assigned a value when declared,
and then that value cannot be changed. Here is the way the above
snippet of code should be written:

const int Dollar = 122;

int nYen = nDollars * Dollar;

Declaring a variable as const prevents us from inadvertently changing


its value:

const int nYenPerDollar = 122;


nYenPerDollar = 123; // compiler
error!
✓ Some programmers prefer to use all upper-case names for const
variables (to match the style of #defined values).
✓ However, we will use normal variable naming conventions,
which is more common.
✓ Const variables act exactly like normal variables in every case
except that they cannot be assigned to.
30

10 Basic Data types in C++

✓ A data type determines the type and the operations that can be
performed on the data.
✓ C++ provides various data types and each data type is
represented differently within the computer's memory.
✓ The various data types provided by C++ are built-in data types,
derived data types and user-defined data types as shown in
Figure.

Built-In Data Types

✓ The basic (fundamental) data types provided by c++ are integral,


floating point and void data type.
✓ Among these data types, the integral and floating-point data
types can be preceded by several type modifiers.
✓ These modifiers (also known as type qualifiers) are the keywords
that alter either size or range or both of the data types.
✓ The various modifiers are short, long, signed and unsigned. By
default the modifier is signed.
✓ In addition to these basic data types, ANSI C++ has introduced
two more data types namely, bool and wchar_t.

Integral Data Type: The integral data type is used to store integers
and includes char (character) and int (integer) data types.
Char: Characters refer to the alphabet, numbers and other characters
(such as {, @, #, etc.) defined in the ASCII character set.
31

✓ In C++, the char data type is also treated as an integer data type
as the characters are internally stored as integers that range in
value from -128 to 127.
✓ The char data type occupies 1 byte o f memory (that is, it holds
only one character at a time).
✓ The modifiers that can precede char are signed and unsigned.
The various character data types with their size and range are
listed in Table

Int: Numbers without the fractional part represent integer data. In


C++, the int data type is used to store integers such as 4, 42, 5233, -
32, -745. Thus, it cannot store numbers such as 4.28, -62.533. The
various integer data types with their size and range are listed in Table
32

Floating-point Data Type: A floating-point data type is used to store


real numbers such as 3 .28, 64. 755765, 8.01, -24.53. This data type
includes float and double' data types. The various floating -point data
types with their size and range are listed in Table

Void:
✓ The void data type is used for specifying an empty parameter list
to a function and return type for a function.
✓ When void is used to specify an empty parameter list, it
indicates that a function does not take any arguments and
when it is used as a return type for a function, it indicates that
a function does not return any value.
✓ For void, no memory is allocated and hence, it cannot store
anything. As a result, void cannot be used to declare simple
variables, however, it can be used to declare generic pointers.

Bool and wchar_t :


✓ The bool data type can hold only Boolean values, that is; either
true or false, where true represents 1 and false represents 0.
✓ It requires only one bit of storage, however, it is stored as an
integer in the memory.
✓ Thus, it is also considered as an integral data type.
✓ The bool data type is most commonly used for expressing the
results of logical operations performed on the data.
33

✓ It is also used as a return type of a function indicating the


success or the failure of the function.
✓ In addition to char data type, C++ provides another data type
wchar_t which is used to store 16- bit wide characters.
✓ Wide characters are used to hold large character sets associated
with some non-English languages.
Derived Data Types:

Data types that are derived from the built-in data types are known as
derived data types.
The various derived data types provided by C++ are arrays, junctions,
references and pointers.
Array
✓ An array is a set of elements of the same data type that are
referred to by the same name.
✓ All the elements in an array are stored at contiguous (one after
another) memory locations and each element is accessed by a
unique index or subscript value.
✓ The subscript value indicates the position of an element in an
array.

Function
✓ A function is a self-contained program segment that carries out
a specific well-defined task. In C++, every program contains one
or more functions which can be invoked from other parts of a
program, if required.

Reference
✓ A reference is an alternative name for a variable.
✓ That is, a reference is an alias for a variable in a program.
✓ A variable and its reference can be used interchangeably in a
program as both refer to the same memory location.
✓ Hence, changes made to any of them (say, a variable) are
reflected in the other (on a reference).
34

Pointer
✓ A pointer is a variable that can store the memory address of
another variable.
✓ Pointers allow to use the memory dynamically.
✓ That is, with the help of pointers, memory can be allocated or
de-allocated to the variables at run-time, thus, making a
program more efficient.

11 User-Defined Data Types

Various user-defined data types provided by C++ are structures,


unions, enumerations and classes.

Structure, Union and Class:


✓ Structure and union are the significant features of C language.
✓ Structure and union provide a way to group similar or
dissimilar data types referred to by a single name.
✓ However, C++ has extended the concept of structure and union
by incorporating some new features in these data types to
support object -oriented programming.
✓ C++ offers a new user-defined data type known as class, which
forms the basis of object-oriented programming.
✓ A class acts as a template which defines the data and functions
that are included in an object of a class.
✓ Classes are declared using the keyword class.
✓ Once a class has been declared, its object can be easily created.

Enumeration:
✓ An enumeration is a set of named integer constants that specify
all the permissible values that can be assigned to enumeration
variables.
✓ These set of permissible values are known as enumerators.

For example, consider this statement.

enum country {US, UN, India, China}; // declaring an enum

✓ In this statement, an enumeration data-type country (country is


a tag name) , consisting of enumerators US, UN and so on, is
declared.
35

✓ Note that these enumerators represent integer values, so any


arithmetic operation can be performed on them.
✓ By default, the first enumerator in the enumeration data type is
assigned the value zero.
✓ The value of subsequent enumerators is one greater than the
value of previous enumerator.
✓ Hence, the value of US is 0, value of UN is 1 and so on.
✓ However, these default integer values can be overridden by
assigning values explicitly to the enumerators as shown here.

enum country {US, UN=3, India, china} ;

✓ In this declaration, the value of US is O by default, the


value of UN is 3, India is 4 and soon. Once an enum
type is declared, its variables can be declared using
this statement.
country countryl, country2;

These variables countryl, country2 can be assigned any of the values


specified in enum declaration only. For example, consider these
statements.

countryl India; // valid

country2 Japan; // invalid

Though the enumerations are treated as integers internally in C++,


the compiler issues a warning, if an int value is assigned to an enum
type. For example, consider these statements.

Country1 = 3; //warning
Country1 = UN; / /valid

Country1 = (country) 3; / /valid

C++ also allows creating special type of enums known as anonymous


enums, that is, enums without using tag name as shown in this
statement.

enum {US, UN=3, India, China};


36

The enumerators of an anonymous enum can be used


directly in the program as shown here.
int count = US;

The typedef Keyword

✓ C++ provides a typedef feature that allows to define new data


type names for existing data types that may be built-in, derived
or user-defined data types.
✓ Once the new name has been defined, variables can be declared
using this new name.
For example, consider this declaration.

typedef int integer;


✓ In this declaration, a new name integer is given to the data type
into This new name now can be used to declare integer
variables as shown here.
integer i, j, k;
❖ Note that the typedef is used in a program to contribute to the
development of a clearer program. Moreover, it also helps in
making machine-dependent programs more portable.
37

12 Variables in C++

✓ A variable is an identifier that refers to the data item stored at a


particular memory location.
✓ This data item can be accessed in the program simply by using
the variable name.
✓ The value of a variable can be changed by assigning different
values to it at various places in a program.
✓ A variable name should be carefully chosen by the programmer
so that its use is reflected in a useful way in the entire
program.
✓ Variable names are case sensitive.
Examples of variable names are: Sun, number, Salary, Emp_name,
average etc.
Any variable declared in a program should confirm to the following
points:
✓ They must always begin with a letter, although some systems
permit underscore as the first character.
✓ The length of a variable must not be more than 8 characters.
✓ White space is not allowed and o A variable should not be a
Keyword o It should not contain any special characters.

Examples of Invalid Variable names are: 123, (area), 6th, %abc etc.

Definition: "Variables are those quantities whose value can vary


during the execution of the program”

Declaration of Variables

✓ Variables must be declared in a program before they are used.


Variables can be declared at the start of any block of code, but
most are found at the start of each function.
✓ Most local variables are created when the function is called, and
are destroyed on return from that function Variables uses the
primary storage area.
✓ Variables are basically memory locations which are given names
and these locations are refereed in the program by variable
names to read and write data in it.
✓ Variables are used for identification for entering the information
or data.
38

✓ In variable you can enter integer value or real or character value


(string value) according to the requirement.
✓ So we can say that variable are either of integers or float type or
string type according to the data type used in C++
programming.
✓ Variables are used in C++ programs for reading data from the
keyboard or from the file, process some formula and printing
the information.
✓ In C++ language variables have no length for declaration, but
some compilers allow either 31 character or 8 character long
variables.
✓ It contains the name of a valid identifier. The syntax for
declaring a variable is

data_type variable_name;

For example, a variable a of type int can be declared using this


statement. int a;
At the time of the variable declaration, more than one variable of the
same data type can be declared in a single statement.
For example, consider this statement.

int x, y, z;

Note that in C++, it is not necessary to declare the variables in the


beginning of a program as required in C. It can be declared at the
place where it is used first.

Initialization of Variables

✓ Declaration of variables allocates sufficient memory for


variables.
✓ However, it does not store any data in the variables.
✓ To store data in variables, they need to be initialized at the time
of declaration.
✓ For example, consider this statement.

int i=10;

In this statement, a variable i of the integer type is declared and


initialized with a value of 10. We can assign a value to a variable by
using assignment operator (=).
39

✓ Variables can either be initialized at the compile-time or at


the run-time initialization at the compile time using a
constant is known as static initialization.
✓ variables can also be initialized at the run-time using
expressions initialization of variables at the runtime is
known as dynamic initialization.

Example A program to demonstrate static and dynamic initialization

#include<iostream>
using namespace std;
int main ()
{
int num1 = 5, num2 = 6; //static initialization using constant
int num3 = num1 + num2; // Dynamic initialization using
expression cout<<num3;
return 0;
}

The const qualifier:


✓ When the qualifier const precedes a data type in the declaration
of a variable, it implies that the value of the variable cannot be
changed throughout the program.
✓ For example, consider this statement.

const float pie_val = 3.14;

✓ The qualifier const with variable pie_val ensures that the


program cannot alter its value inadvertently.
✓ If any attempt to alter the value of pie_val is made within a
program, a compile-time error is generated.
✓ Moreover, if any data type is not specified with the const
qualifier, by default it is int.
✓ For example, consider these statements.
const int max = 20; // Both these statements
const max = 20; // are equivalent.
40

• In C++, the variable declared as a constant must be initialized at the


time of its declaration. While in C, const value is automatically
initialized to 0 if it is not initialized by the user.
• In C++, const can be used in expressions. For example, consider these
statements.
const int max
=20; char
name [max] ;
However, it is invalid in
C.
• In C++, by default, a const value is local to the file in which it is
declared. However, it can be made global by explicitly defining it as
an extern variable, as given here.
extern canst max=10;
✓ In C, by default, canst value is recognized globally, that is, it is
also visible outside the file in which it is declared.
✓ However, it can be made local by declaring it as static.
41

13 Reference Variables

• A Reference variable, a new kind of variable that is introduced


in C++ provides an alias for an already defined variable.
• Like other variables, reference variables must be declared in a
program before they are used.
• The syntax for declaring a reference variable is

data_type & refname = varname;

where, data_type = any valid C++ data type


& = reference operator refname = the name of the reference
variable being declared
varname = the name of the variable whose reference is being
declared
• A reference variable provides an alias for a previously defined
variable.
Example:- If we make the variable sum a reference to the variable
total, the sum & total can be used interchangeably to represent hat
variable.
• Reference variable is created as:-
data type & reference name = variable name.
Ex:- int sum = 20 ;
int &total = sum;
Here total is the alternative name declared to represent the
variable sum. Both variable refer to the same data object in
memory.
• A reference variable must be initialized at the time of declaration.
• C+ + assigns additional meaning to the symbol "&".
• Here & is not an address operation.
• The notation int & means reference to int. A major application of
reference variable is in passing arguments to functions.

Example : Program to demonstrate the use of reference variable


42

#include<iostream>

using namespace std;

int main ( )

float cost = 200;

float &price = cost; // Declaration of Reference variable


cout<<"price: " <<price<<"\n";
price = price+20;
cout<<"cost: " <<cost<<"\n";
cout<<"price: " <<price;
return 0;

The output of the program is


price: 200
cost: 220
price: 220
43

14 Operators in C++

C+ had rich set of operators. Some of the new operators in c+


are-
1. Scope resolution operators -
::
2. pointer to member declarator -
: :*
3. pointer to member operator- -
>*
4. pointer to member operator- .*.
5. delete memory release operator- delete
6. Line feed operator-endl
7. Memory allocation operator-new.
8. Field width operator-setw.
9. Type cast operator
44

15 Scope resolution Operator : :


C+ is a block - structured language.
1)The scope of the variable extends from the point of its declaration til
the end of the block containing the declaration.
2) Consider following program.
{

int x = 1;

==

}= ==

int x
= 2;

} = ==

The two declaration of x refer to two different memory locations


containing different values. Blocks in c+ are often nested. Declaration
in a inner block hides a declaration of the same variable in an outer
block.
3) In C, the global version of a variable cannot be accessed from within
the inner block.
C+ resolves this problem by using scope resolution operator (: :),
because this operator allows access to the global version of a variable.
4) Consider following program.
45

# include<iostream>

using namespace std;

int m = 10;

main ( )

int m = 20;

int k = m;

int m = 30;

cout << "K = "< < k;

cout << "m = "<< m;

cout << : : m = "<< : : m;

cout < <"m = "<< m;

cout < <" : : m ="< < : : m;

The output of program is k = 20

m = 30 ::m=10 m=20 ::m=10

In the above program m is declared at three places. And : : m will


always refer to global m.
5) A major application of the scope resolution operator is in the
classes to identify the class to which a member functions belongs.
46

16 Member dereferencing operators

✓ C+ permits us to define a class containing various types of data


& functions as members.
✓ C+ also permits us to access the class members through
pointers. C+ provides a set of three pointer.
C+ provides a set of three pointers to member operators.
1) To access a pointer to a member of a class- : :* .
2) To access a member using object name & a pointer to that
member -.* .
3) To access a member using a pointer in the object & a pointer
to the member- -->*.
47

17 Memory management operators:


1) We use dynamic allocation techniques when it is not known in
advance how much of memory space is nedded.
C+ supports two unary operators new and delete that perform the task
of allocating & freeing the memory. 2) An object can be created by
using new and destroyed by using delete. A data object created inside
a block with new, will remain existence until it is explicitly destroyed
by using delete.
3) It takes following form.
variable = new data type
The new operator allocated sufficient memory to hold a data object of
type data-type & returns the address of the object.
EX - int *p;
p = new int.
Where p is a pointer of type int. Here p must have already been
declared as pointer of appropriate types.
4) New can be used to create a memory space for any data type
including user defined type such al array, classes etc.
Ex- int * p = new int [10]
Creates a memory space for an array of 10 integers.
5) When a data object is no longer needed, it is destroyed to release
the memory space for reuse.
The general form is
delete variable.
If we want to free a dynamically allocated array, we must use
following form.
delete [size] variable.
The size specifies the no of elements in the array to be freed.
6) The new operator has following advantages over the function
malloc() in c -.
1. It automatically computes the size of the data object. None need
to use sizeOf() operator.
2. If automatically returns the correct pointer type, so that here is
no need to use a type cast.
3. new and delete operators can be overloaded.
4. It is possible to initialize the object while creating the memory
space.
48

Manipulators
Manipulators are operators that are used to format he data display.
There are two important manipulators.
1) endl
2) setw

1) endl:

This manipulator is used to insert a linefeed into an output. It has


same effect as using \n for newline.

Ex- cout< <"a="< < a << endl <<"n="< < n<< endl< <"p="<<p< endl;
OUTPUT:
a = 2568
n = 34
p = 275

2 Setw :

With the setw, we can specify a common field width for all the
numbers and force them to print with right alignment.
EX : cout< <setw (5)< < sum< endl;
The manipulator setw(5) specifies a field width of 5 for printing the
value of variable sum the value is right justified.

3 5 6
Type cast operator:
C+ permits explicit type conversion of variables or expressions using
the type cast operator.
Syntax - type name (expression)
Ex : avg = sum/float(i)
Here a type name behaves as if it is a function for converting
values to a designated type
49

18 Storage classes

Storage classes are used to specify the lifetime and scope of variables.
How storage is allocated for variables and How variable is treated by
complier depends on these storage classes.
These are basically divided into 5 different types :

1. Global variables
2. Local variables
3. Register variables
4. Static variables
5. Extern variables

Global Variables
These are defined at the starting , before all function bodies and are
available throughout the program.
using namespace std;
int globe; // Global variable
void func();
int main()
{
.....
}

Local variables
They are defined and are available within a particular scope. They are
also called Automatic variablebecause they come into being when
scope is entered and automatically go away when the scope ends.
The keyword auto is used, but by default all local variables are auto,
so we don't have to explicitly add keyword auto before variable
dedaration. Default value of such variable is garbage.
50

Register variables
This is also a type of local variable. This keyword is used to tell the
compiler to make access to this variable as fast as possible. Variables
are stored in registers to increase the access speed.
But you can never use or compute address of register variable and
also , a register variable can be declared only within a block, that
means, you cannot have global or static register variables.

Static Variables
Static variables are the variables which are initialized & allocated
storage only once at the beginning of program execution, no matter
how many times they are used and called in the program. A static
variable retains its value until the end of program.
void fun()
{
static int i = 10;
i++;
cout << i;
}
int main()
{
fun(); // Output = 11
fun(); // Output = 12
fun(); // Output = 13
}
As, i is static, hence it will retain its value through function calls, and
is initialized only once at the beginning.
Static specifiers are also used in classes, but that we will learn later.
Extern Variables
This keyword is used to access variable in a file which is declared &
defined in some other file, that is the existence of a global variable in
one file is declared using extern keyword in another file.
51
52

NOTES:-MODULE-1
53
54
55

Module II
Control Structures.
Classes and Objects: Specifying a class, defining member functions,
C++ program with class, private member functions, arrays within
class, memory allocation for objects, static data members, static
member functions, arrays of objects, returning objects.
Functions in C++: main function, function prototyping, call by
reference, return by reference, inline functions, default arguments.

1. Control structures

Decision making in C++:


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,

• if statement
• switch statement
• conditional operator statement
• goto statement

Decision making with if statement


The if statement may be implemented in different forms depending on
the complexity of conditions to be tested. The different forms are,

1. Simple if statement
2. If....else statement
3. Nested if....else statement
4. else if statement
56

Simple if statement
The general form of a simple if statement is,
if( expression )
{
statement-inside;
}
statement-outside;
If the expression is true, then 'statement-inside' it will be executed,
otherwise 'statement-inside' is skipped and only 'statement-outside' is
executed.
Example :
#include< iostream.h>
int main( )
{
int x,y;
x=15;
y=13;
if (x > y )
{
cout << "x is greater than y";
}
}
Output :
x is greater than y
if...else statement
The general form of a simple if...else statement is,
if( expression )
{
statement-block1;
}
else
{
statement-block2;
}
57

If the 'expression' is true, the 'statement-block1' is executed, else


'statement-block1' is skipped and 'statement-block2' is executed.
Example :
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";
}
}
Output :
y is greater than x

Nested if....else statement


The general form of a nested if...else statement is,
if( expression )
{
if( expression1 )
{
statement-block1;
}
else
{
statement-block2;
}
58

}
else
{
statement-block3;
}
if 'expression' is false the 'statement-block3' will be executed,
otherwise it continues to perform the test for 'expression 1' . If the
'expression 1' is true the 'statement-block1' is executed otherwise
'statement-block2' is executed.
Example :
void main( )
{
int a,b,c;
clrscr();
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";
}
59

else
{
printf("c is greatest");
}
}
getch();
}

else-if ladder
The general form of else-if ladder is,
if(expression 1)
{
statement-block1;
}
else if(expression 2)
{
statement-block2;
}
else if(expression 3 )
{
statement-block3;
}
else
default-statement;
The expression is tested from the top(of the ladder) downwards. As
soon as the true condition is found, the statement associated with it is
executed.
60

Example :
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";
}
getch();
}
61

C++ switch...case syntax


switch (n)
{
case constant1:
// code to be executed if n is equal to constant1;
break;
case constant2:

// code to be executed if n is equal to constant2;

break;

default:

// code to be executed if n doesn't match any constant

When a case constant is found that matches the switch expression,


control of the program passes to the block of code associated with that
case.

In the above pseudocode, suppose the value of n is equal


to constant2. The compiler will execute the block of code associated
with the case statement until the end of switch block, or until
the break statement is encountered.

The break statement is used to prevent the code running into the next
case.
62

Looping in C++
In any programming language, loops are used to execute a set of
statements repeatedly until a particular condition is satisfied.

How it works

A sequence of statement is executed until a specified condition is


true. This sequence of statement to be executed is kept inside the
curly braces { } known as loop body. After every execution of loop
body, condition is checked, and if it is found to be true the loop body
is executed again. When condition check comes out to be false, the
loop body will not be executed.

There are 3 type of loops in C++ language

1. while loop
2. for loop
3. do-while loop
63

while loop
while loop can be address as an entry control loop. It is completed in
3 steps.

• Variable initialization.( e.g int x=0; )


• condition( e.g while( x<=10) )
• Variable increment or decrement ( x++ or x-- or x=x+2 )

Syntax :
variable initialization ;
while (condition)
{
statements ;
variable increment or decrement ;
}

for loop
for loop is used to execute a set of statement repeatedly until a
particular condition is satisfied. we can say it an open ended
loop. General format is,
for(initialization; condition ; increment/decrement)
{
statement-block;
}
In for loop we have exactly two semicolons, one after initialization and
second after condition. In this loop we can have more than one
initialization or increment/decrement, separated using comma
operator. for loop can have only one condition.
64

Nested for loop


We can also have nested for loop, i.e one for loop inside
another for loop. Basic syntax is,
for(initialization; condition; increment/decrement)
{
for(initialization; condition; increment/decrement)
{
statement ;
}
}

do while loop
In some situations it is necessary to execute body of the loop before
testing the condition. Such situations can be handled with the help
of do-while loop. do statement evaluates the body of the loop first and
at the end, the condition is checked using while statement. General
format of do-while loop is,
do
{
....
.....
}
while(condition);

Jumping out of loop


Sometimes, while executing a loop, it becomes necessary to skip a
part of the loop or to leave the loop as soon as certain condition
becocmes true, that is jump out of loop. C language allows jumping
from one statement to another within a loop as well as jumping out of
the loop.
65

1) break statement
When break statement is encountered inside a loop, the loop is
immediately exited and the program continues with the statement
immediately following the loop.
2) continue statement
It causes the control to go directly to the test-condition and then
continue the loop process. On encountering continue, cursor leave the
current cycle of loop, and starts with the next cycle.
66

2 Class Declaration or Definition

• A class is an organization of data and functions which


• operate on them.
• Data types are called data members and the functions are called
member functions.
• The combination of data members and member functions
constitute a data object or simply an object.

The general syntax or general form of the class declaration is as


follows:

class <name of class>


{
private:
data members;
member functions( );
public:
data members;
member functions ( );
protected:
data members;
member functions( );
};
main( )
{
<name of class> obj1;
obj1.member function( );
obj1.member function( );
}
(i) Class name or name of class

• It is mainly the name given to a particular class.


• It serves as a name specifier for the class, using which we can
create objects.
• The class is specified by keyword "class".
For example: class Circle

Here Circle is the class name.


67

(ii) Data Members

• These are the data-type properties that describe the


characteristics of a class.
• We can declare any number of data members of any type in a
class.
• We can say that the variables in C and data members in C++.

For example: float area;

(iii) Member Functions

• These are the various operations that can be performed to data


members of that class.
• We can declare any number of member functions of any type in
a class.
• Member functions are access using object and dot operator.

For example:

void read( );

void display( );

How member function access: cl.read();

Here c1 is object of class circle and operator dot (.) is used to access
member functions.

(iv) Access Specifiers

• Access Specifiers are used to identify access rights for the data
members and member functions of the class.
• Depending upon the access level of a class member, access to it
is allowed or denied.
68

There are three main types of access specifiers in C++


programming language:

1. Private:

A private member within a class denotes that only members of the


same class have accessibility. The private member is not accessible
from outside the class.

class PrivateAccess
{
private: // private access specifier
int x; // Data Member Declaration
void display(); // Member Function decaration

2. Public:

Public members are accessible from outside the class.

class PublicAccess
{
public: // public access specifier
int x; // Data Member Declaration
void display(); // Member Function decaration
}

3. Protected:

A protected access specifier is a stage between private and public


access. If member functions defined in a class are protected, they
cannot be accessed from outside the class but can be accessed from
the derived class (inheritance).
69

class ProtectedAccess
{
protected: // protected access specifier
int x; // Data Member Declaration
void display(); // Member Function decaration
}

• main() main function is where a program starts execution.


• main () program is the C++ program's main structure in which we
process some statements.

• The main function usually organizes at a high level the functionality of
the rest of the program.

The general syntax is:

main ( ) Beginning of the Main Program: Left Brace {

(The beginning of the main program can be done by using left curly
brace "{").

(i) Object declaration part

• We can declare objects of class inside the main program or outside


the main program.
• A class declaration only uses to builds the structure of an object.
• The data members and member functions are combined in the class.
• The declaration of objects is same as declaration of variables of basic
data types.
• Defining objects of class data type is known as class instantiation
(instances of class).
• When we create objects during that moment, memory is allocated to
them.

For example: c1 is the object of the class Circle.


70

We can create any number of objects of a given class.

(ii) Accessing member functions (using dot operator)

• The member function define in the class are access by using dot
(.) operator.
• Suppose we have two-member functions void read () and void
display ().
• We have to access these members function in the main
program.

The general syntax is:

Obj1. member function();

For example: c1.read();

Here c1 is object and read() is the member function of class Circle ..

Ending of The Main Program: Right Brace}

(The right curly brace "}" is used to end the main program).
71

Accessing Data Members of Class:


Accessing a data member depends solely on the access control of that
data member. If its public, then the data member can be easily
accessed using the direct member access (.) operator with the object of
that class.
If, the data member is defined as private or protected, then we cannot
access the data variables directly. Then we will have to create special
public member functions to access, use or initialize the private and
protected data members. These member functions are also
called Accessors and Mutator methods
or getter and setter functions.

Accessing Public Data Members


Following is an example to show you how to initialize and use the
public data members using the dot (.) operator and the respective
object of class.
class Student
{
public:
int rollno;
string name;
};
int main()
{
Student A;
Student B;
A.rollno=1;
A.name="Adam";
B.rollno=2;
B.name="Bella";
cout <<"Name and Roll no of A is :"<< A.name << A.rollno;
cout <<"Name and Roll no of B is :"<< B.name << B.rollno;
}
72

Accessing Private Data Members


To access, use and initialize the private data member you need to
create getter and setter functions, to get and set the value of the data
member.
The setter function will set the value passed as argument to the
private data member, and the getter function will return the value of
the private data member to be used. Both getter and setter function
must be defined public.
Example :
class Student
{
private: // private data member
int rollno;

public: // public accessor and mutator functions


int getRollno()
{
return rollno;
}

void setRollno(int i)
{
rollno=i;
}
};
int main()
{
Student A;
A.rollono=1; //Compile time error
cout<< A.rollno; //Compile time error
A.setRollno(1); //Rollno initialized to 1
cout<< A.getRollno(); //Output will be 1
}
73

So this is how we access and use the private data members of any
class using the getter and setter methods. We will discuss this in more
details later.

Accessing Protected Data Members


Protected data members, can be accessed directly using dot (.)
operator inside the subclass of the current class, for non-subclass we
will have to follow the steps same as to access private data member.
74

Arrays within a Class

• Arrays can be declared as the members of a class.


• The arrays can be declared as private, public or protected
members of the class.
• To understand the concept of arrays as members of a class,
consider this example.

A program to demonstrate the concept of arrays as class members

Example:
#include<iostream>
const int size=5;
class student
{
int roll_no;
int marks[size];
public:
void getdata ();
void tot_marks ();
} ;

void student :: getdata ()


{
cout<<"\nEnter roll no: ";
Cin>>roll_no;
for(int i=0; i<size; i++)
{
cout<<"Enter marks in subject"<<(i+1)<<": ";
cin>>marks[i] ;
}
void student :: tot_marks() //calculating total marks
{
int total=0;
for(int i=0; i<size; i++)
total+ = marks[i];
cout<<"\n\nTotal marks "<<total;
}
75

void main()
{
student stu;
stu.getdata() ;
stu.tot_marks() ;
getch();
}

Output:
Enter roll no: 101
Enter marks in subject 1: 67
Enter marks in subject 2 : 54
Enter marks in subject 3 : 68
Enter marks in subject 4 : 72
Enter marks in subject 5 : 82
Total marks = 343
76

Memory Allocation

• Many times, we are not aware in advance how much memory


will need to store particular information in a defined variable
and the size of required memory can be determined at run time.
• You can allocate memory at run time within the heap for the
variable of a given type using a special operator in C++ which
returns the address of the space allocated. This operator is
called new operator.
• If you are not in need of dynamically allocated memory
anymore, you can use delete operator, which de-allocates
memory previously allocated by new operator.

Memory Allocation for Objects:

• Objects are no different from simple data types.


• For example, following code where we are going to use an array
of objects to clear your concept:

Example:
#include <iostream>
class Box
{
public:
Box() {
cout << "Constructor is called!" <<endl;
}
~Box() {
cout << "Destructor is called!" <<endl;
}
};

void main( )
{
Box* myBoxArray = new Box[4];
delete [] myBoxArray; // Delete array
getch();
}
77

Output:
Constructor is called!
Constructor is called!
Constructor is called!
Constructor is called!
Destructor is called!
Destructor is called!
Destructor is called!
Destructor is called!
78

Static Keyword

Static is a keyword in C++ used to give special characteristics to an


element. Static elements are allocated storage only once in a program
lifetime in static storage area. And they have a scope till the program
lifetime. Static Keyword can be used with following,

1. Static variable in functions


2. Static Class Objects
3. Static member Variable in class
4. Static Methods in class

Static variables inside Functions

Static variables when used inside function are initialized only once,
and then they hold there value even through function calls.

These static variables are stored on static storage area , not in stack.

void counter()
{
static int count=0;
cout << count++;
}

int main(0
{
for(int i=0;i<5;i++)
{
counter();
}
}

Output :

01234

Let's se the same program's output without using static variable.

void counter()
{
int count=0;
cout << count++;
}
79

int main()
{
for(int i=0;i<5;i++)
{
counter();
}
}

Output :

00000

If we do not use static keyword, the variable count, is reinitialized


everytime when counter() function is called, and gets destroyed each
time when counter() functions ends. But, if we make it static, once
initialized count will have a scope till the end of main() function and it
will carry its value through function calls too.

If you don't initialize a static variable, they are by default initialized to


zero.

Static class Objects

Static keyword works in the same way for class objects too. Objects
declared static are allocated storage in static storage area, and have
scope till the end of program.

Static objects are also initialized using constructors like other normal
objects. Assignment to zero, on using static keyword is only for
primitive datatypes, not for user defined datatypes.

class Abc
{
int i;
public:
Abc()
{
i=0;
cout << "constructor";
}
~Abc()
{
cout << "destructor";
}
};
80

void f()
{
static Abc obj;
}

int main()
{
int x=0;
if(x==0)
{
f();
}
cout << "END";
}

Output :

constructor END destructor

You must be thinking, why was destructor not called upon the end of
the scope of if condition. This is because object was static, which has
scope till the program lifetime, hence destructor for this object was
called when main() exits.

Static data member in class

Static data members of class are those members which are shared by
all the objects. Static data member has a single piece of storage, and
is not available as separate copy with each object, like other non-
static data members.

Static member variables (data members) are not initialied using


constructor, because these are not dependent on object initialization.

Also, it must be initialized explicitly, always outside the class. If not


initialized, Linker will give error.

class X
{
static int i;
public:
X(){};
};

int X::i=1;
81

int main()
{
X obj;
cout << obj.i; // prints value of i
}

Once the definition for static data member is made, user cannot
redefine it. Though, arithmetic operations can be performed on it.

NOTES:

• A data member of a class can be qualified as static.


A static member variable has certain special characteristics.
They are:

• It is initialized to zero when the first object of its class is


created. No other initialization is permitted.
• Only one copy of that member is created for the entire class and
is shared by all the objects of that class, no matter how many
objects are created.
• It is visible only within the class, but its lifetime is the entire
program.
• Static variables are normally used to maintain values common
to the entire class.
• The type and the scope of each static member variable must be
defined outside the class definition.
• Because , the static data members are stored separately rather
than as a part of an object.
• They are also known as class variables.
82

Sharing of a static data member

Static member functions:

A member function that is declared static has the following properties:

• A static function can have access to only other static members


(functions or variables) declared in the same class.
• A static member function can be called using the class
name(instead of its objects) as follows:
class-name :: function-name;

These functions work for the class as whole rather than for a
particular object of a class.

It can be called using an object and the direct member access .


operator. But, its more typical to call a static member function by
itself, using class name and scope resolution :: operator.

Example :

class X
{
public:
static void f(){};
};
83

int main()
{
X::f(); // calling member function directly with class name
}

These functions cannot access ordinary data members and member


functions, but only static data members and static member functions.

It doesn't have any "this" keyword which is the reason it cannot access
ordinary members. We will study about "this" keyword later.

Array of class objects

Array is a collection of similar type of data’s that are referenced by a


common name. Similarly, array of class objects means a collection of
similar type of objects referenced by a common name. Hence, an array
having class type element is known as array of object. The syntax for
defining the array of class objects is as follows:-

Class_name object_name [size];

Where, size is a size of the array of class objects.

E.g. A program to input ‘n’ student’s information such as roll o, age,


sex, height and weight and display the data at the end.

[Note: Here, class student is defined as an array of class objects. This


program shows how to create an array of class objects and how to
access these data member and member functions in c++]

#include<iostream.h>
#include<conio.h>
class student
{
private:
int rollno, age;
char sex;
float weight, height;
public:
void get info ()
{
cout<<”\n enter roll number”;
cin>>rollno;
cout<<”\n enter age”;
cin>>age;
cout<<”\n enter sex”;
cin>>sex;
84

cout<<”\n enter weight”;


cin>>weight;
cout<<”\n enter height”;
cin>>height;
}
void disinfo ()
{
cout<<”\n roll no=”<<rollno;
cout<<”\n age=”<<age;
cout<<”\n sex=”<<sex;
cout<<”\n height=”<<height;
cout<<”n weight=”<<weight;
}

void main ()

{
student obj [100];
int i, n;
cout<<”how many student?”;
cin>>n;
cout<<”\n enter the information:”;
for (i=0; i<n;i++)
{
obj [i].disinfo ();
}
getch ();
}
85

Example 2:
#include <iostream>
#include <string>

using namespace std;

class Student
{
string name;
int marks;
public:
void getName()
{
getline( cin, name );
}
void getMarks()
{
cin >> marks;
}
void displayInfo()
{
cout << "Name : " << name << endl;
cout << "Marks : " << marks << endl;
}
};

int main()
{
Student st[5];
for( int i=0; i<5; i++ )
{
cout << "Student " << i + 1 << endl;
cout << "Enter name" << endl;
st[i].getName();
cout << "Enter marks" << endl;
st[i].getMarks();
}

for( int i=0; i<5; i++ )


{
cout << "Student " << i + 1 << endl;
st[i].displayInfo();
}
return 0;
}
86

Student st[5]; - We created an array of 5 objects of the Student class


where each object represents a student having a name and marks.
The first for loop is for taking the input of name and marks of the
students. getName() and getMarks() are the functions to take the
input of name and marks respectively.
The second for loop is to print the name and marks of all the 5
students. For that, we called the displayInfo() function for each
student.
87

Returning Objects

• A function cannot only receive objects as arguments but also


can return them.
• Following example illustrates how an object can be created
(within a function) and returned to another function.

#include < iostream.h >


// Declaration of the function to be made as friend for the C++

int AddToFriend(int x);


class CPP_Tutorial
{
int private_data;
friend int AddToFriend(int x);
public:
CPP_Tutorial()
{
private_data =5;
}
};
int AddToFriend(int x)
{
CPP_Tutorial var1;
return var1.private_data + x;}

int main() {
cout << “Added Result for this C++ tutorial: “<< AddToFriend(4) <<
endl;
}
88

Functions in C++
main function, function prototyping, call by reference, return by
reference, inline functions, default arguments.

C++ Functions

• A 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.
• You 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 so 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.
• A function is knows as with various names like a method or a
sub-routine or a procedure etc.

Syntax:
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.
89

Function Name:

• This is the actual name of the function.


• The function name and the parameter list together constitute
the function signature.

Parameters:

• When a function is invoked, you pass a value to the parameter.


• This value is referred to as actual parameter or argument.
• The parameter list refers to the type, order, and number of the
parameters of a function.
• Parameters are optional; that is, a function may contain no
parameters.

Function Body:

• The function body contains a collection of statements that


define what the function does.

Example:
#include <iostream>

// function declaration
int max(int num1, int num2);

int main ()
{
// local variable declaration:
int a = 99;
int b = 97;
int ret;

// calling a function to get max value.


ret = max(a, b);

cout << "Max value is : " << ret << endl;

return 0;
}

// function returning the max between two numbers


int max(int num1, int num2)
{
// local variable declaration
int result;
90

if (num1 > num2)


result = num1;
else
result = num2;

return result;
}

Output:

Max value is : 99

Function prototyping

• A function prototype is a function declaration that specifies


the data types of its arguments in the parameter list.
• a function prototype or function interface is a declaration of
a function that specifies the function's name and type
signature (arity, parameter types, and return type), but omits
the function body.
• Prototypes are syntactically distinguished from the old style of
function declaration.
• While a function definition specifies how the function does what
it does (the "implementation"), a function prototype merely
specifies its interface, i.e. what data types go in and come out of
it.
• In a prototype, parameter names are optional (and in C/C++
have function prototype scope, meaning their scope ends at the
end of the prototype), however, the type is necessary along with
all modifiers.
• The two styles can be mixed for any single function, but this is
not recommended. The following is a comparison of the old and
the prototype styles of declaration:
91

Old style:

• Functions can be declared implicitly by their appearance in a


call.
• Arguments to functions undergo the default conversions before
the call.
• The number and type of arguments are not checked.

Prototype style:

• Functions are declared explicitly with a prototype before they


are called.
• Multiple declarations must be compatible, parameter types
must agree exactly.
• Arguments to functions are converted to the declared types of
the parameters.
• Empty parameter lists are designated using the void keyword.
• Ellipses are used in the parameter list of a prototype to indicate
that a variable number of parameters are expected.

Call by Reference

• The call by reference method of passing arguments to a function


copies the reference of an argument into the formal parameter.
• Inside the function, the reference is used to access the actual
argument used in the call.
• This means that changes made to the parameter affect the
passed argument.
• To pass the value by reference, argument reference is passed to
the functions just like any other value.
• So accordingly you need to declare the function parameters as
reference types as in the following function swap(), which
exchanges the values of the two integer variables pointed to by
its arguments.
92

Example:

#include <iostream>

// function declaration
void swap(int &x, int &y);

int main ()
{
// local variable declaration:
int a = 100;
int b = 200;

cout << "Before swap, value of a :" << a << endl;


cout << "Before swap, value of b :" << b << endl;

/* calling a function to swap the values using variable


reference.*/
swap(a, b);

cout << "After swap, value of a :" << a << endl;


cout << "After swap, value of b :" << b << endl;

return 0;
}
OUTPUT:

Before swap, value of a :100


Before swap, value of b :200
After swap, value of a :200
After swap, value of b :100

Return by Reference

• A C++ program can be made easier to read and maintain by


using references rather than pointers.
• A C++ function can return a reference in a similar way as it
returns a pointer.
• When a function returns a reference, it returns an implicit
pointer to its return value.
• This way, a function can be used on the left side of an
assignment statement. For example, consider this simple
program:
93

Example:

#include <iostream>

int n;
int& test();

int main()
{
test() = 5;
cout<<n;
return 0;
}

int& test()
{
return n;
}

OUTPUT:

Note:

• In program above, the return type of function test() is int&.


Hence this function returns by reference. The return statement
is return n; but unlike return by value. This statement doesn't
return value of n, instead it returns variable n itself.
• Then the variable n is assigned to the left side of code test() =
5; and value ofn is displayed.

C++ Inline Functions

• C++ inline function is powerful concept that is commonly used


with classes.
• If a function is inline, the compiler places a copy of the code of
that function at each point where the function is called at
compile time.
94

• To inline a function, place the keyword inline before the


function name and define the function before any calls are made
to the function.
• The compiler can ignore the inline qualifier in case defined
function is more than a line.
• Any change to an inline function could require all clients of the
function to be recompiled because compiler would need to
replace all the code once again otherwise it will continue with
old functionality.
• A function definition in a class definition is an inline function
definition, even without the use of the inline specifier.

Syntax:
inline return-type function-name(arguments)
{
return ( conditions );
}
#include <iostream>

inline int Max(int x, int y)


{
return (x > y)? x : y;
}

// Main function for the program


int main( )
{

cout << "Max (30,40): " << Max(30,40) << endl;


cout << "Max (0,100): " << Max(0,100) << endl;
cout << "Max (700,10): " << Max(700,10) << endl;
return 0;
}
Output:

Max (30,40): 40
Max (0,100): 100
Max (700,10): 700
95

Limitations of Inline Functions

1. Large Inline functions cause Cache misses and affect


performance negatively.
2. Compilation overhead of copying the function body everywhere
in the code on compilation, which is negligible for small
programs, but it makes a difference in large code bases.
3. Also, if we require address of the function in program, compiler
cannot perform inlining on such functions. Because for
providing address to a function, compiler will have to allocate
storage to it. But inline functions doesn't get storage, they are
kept in Symbol table.
96

Default Arguments in C++

• A default argument is a value provided in function declaration


that is automatically assigned by the compiler if caller of the
function doesn’t provide a value for the argument with default
value.
• Following is a simple C++ example to demonstrate use of default
arguments. We don’t have to write 3 sum functions, only one
function works by using default values for 3rd and 4th
arguments.

#include<iostream>

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

/* Drier 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;
getch();
}
Output:

25
50
80
97

Example 2
#include<iostream>
using namespace std;

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

/* Drier program to test above function*/


int main()
{
cout << sum(10, 15) << endl;
cout << sum(10, 15, 25) << endl;
cout << sum(10, 15, 25, 30) << endl;
return 0;
}

Output:

25
50
80
98

Notes: Module2
99
100
101

Module III
More about Functions: Function overloading, friendly functions:
friend function, a function friendly to two classes, objects as function
arguments.
Constructors & Destructors: Constructors, parameterized
constructors, multiple constructors in a class, constructors with
default arguments, copy constructors, dynamic constructors,
destructors.

1.Function Overloading
✓ Two or more functions having same name but different
argument(s) are known as overloaded functions.

✓ We cannot overload function declarations that differ only by


return type.

✓ If any class have multiple functions with same names but


different parameters then they are said to be overloaded.
✓ Function overloading allows you to 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 you have to perform one single operation but
with different number or types of arguments, then you can
simply overload the function.

Ways to overload a function

1. By changing number of Arguments.


2. By having different types of argument.

Number of Arguments different


In this type of function overloading we define two functions with same
names but different number of parameters of the same type. For
example, in the below mentioned program we have made two sum()
functions to return sum of two and three integers.
102

int sum (int x, int y)


{
cout << x+y;
}

int sum(int x, int y, int z)


{
cout << x+y+z;
}

Here sum() function is overloaded, to have two and three arguments.


Which sum() function will be called, depends on the number of
arguments.
int main()
{
sum (10,20); // sum() with 2 parameter will be called

sum(10,20,30); //sum() with 3 parameter will be called


}

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 have two sum() function, first
one gets two integer arguments and second one gets two double
arguments.
103

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

Example 1 function overloading


#include <iostream>

class printData
{
public:
void print(int i) {
cout << "Printing int: " << i << endl;
}
void print(double f) {
cout << "Printing float: " << f << endl;
}
void print(char* c) {
cout << "Printing character: " << c << endl;
}
};

void main(void)
{
printData pd;
// Call print to print integer
pd.print(9);
// Call print to print float
pd.print(100.200);
// Call print to print character
pd.print("Hello C++");
getch();
}

Printing int: 9
Printing float: 100.200
Printing character: Hello C++
105

Example 2 function overloading


#include <iostream>
using namespace std;
void display(int);
void display(float);
void display(int, float);
int main() {
int a = 5;
float b = 5.5;
display(a);
display(b);
display(a, b);
return 0;
}
void display(int var) {
cout << "Integer number: " << var << endl;
}
void display(float var) {
cout << "Float number: " << var << endl;
}
void display(int var1, float var2) {
cout << "Integer number: " << var1;
cout << " and float number:" << var2;
}
OUTPUT:
Integer number: 5
Float number: 5.5
Integer number: 5 and float number: 5.5

Note:
Here, the display() function is called three times with different type or
number of arguments.
106

Friend function

• If a function is defined as a friend function then, the private and


protected data of class can be accessed from that function.
• The complier knows a given function is a friend function by its
keyword friend.
• The declaration of friend function should be made inside the
body of class (can be anywhere inside class either in private or
public section) starting with keyword friend.

Syntax:

class class_name
{
...... .... ........
friend return_type function_name(arguments);
...... .... ........
}

• Now, you can define friend function of that name and that
function can access the private and protected data of that
function.
• No friend keyword is used in the definition.
• For accessing the data, the declaration of a friend function
should be made inside the body of the class (can be anywhere
inside class either in private or public section) starting with
keyword friend.
107

class className
{
... .. ...
friend return_type functionName(argument/s);
... .. ...
}
return_type functionName(argument/s)
{
... .. ...
// Private and protected data of className can be
accessed from
// this function because it is a friend function of
className.
... .. ...
}
/* C++ program to demonstrate the working of friend function.*/
#include <iostream>
using namespace std;
class Distance
{
private:
int meter;
public:
Distance(): meter(0) { }
//friend function
friend int addFive(Distance);
};
// friend function definition
int addFive(Distance d)
{
//accessing private data from non-member function
d.meter += 5;
return d.meter;
}
int main()
{
Distance D;
cout<<"Distance: "<< addFive(D);
return 0;
}
OUTPUT:

Distance: 5

Here, friend function addFive() is declared inside Distance class. So,


the private data meter can be accessed from this function.
108

Example 2: Addition of members of two different classes using friend


Function
#include <iostream>
using namespace std;

// forward declaration
class B;
class A {
private:
int numA;
public:
A(): numA(12) { }
// friend function declaration
friend int add(A, B);
};

class B {
private:
int numB;
public:
B(): numB(1) { }
// friend function declaration
friend int add(A , B);
};

// Function add() is the friend function of classes A and B


// that accesses the member variables numA and numB
int add(A objectA, B objectB)
{
return (objectA.numA + objectB.numB);
}

int main()
{
A objectA;
B objectB;
cout<<"Sum: "<< add(objectA, objectB);
return 0;
}
Sum: 13
In this program, classes A and B have declared add() as a friend function. Thus, this
function can access private data of both class.

Here, add() function adds the private data numA and numB of two objects objectA
and objectB, and returns it to the main function.

To make this program work properly, a forward declaration of a class class B should
be made as shown in the above example.

This is because class B is referenced within the class A using code: friend int
add(A , B);.
109

Objects as function arguments


Like any order data type, Objects of a class can be passed as Function
Arguments. Objects of a class can be passed to the following function :-
1) Member Functions, 2) Non-Member Functions, 3) Friend Functions.
Member Functions and Friend Functions can access private and
protected members of the passed objects Whereas Non-Member
Functions cannot access private and protected members of the passed
objects.
#include <iostream>
using namespace std;
class Convert
{
float cm, m;
public :
void input()
{
cout << "\n \t Please enter value in meter to convert in
centimeter : ";
cin >> m;
}
void conv_cm(Convert obj)
{
obj.cm=obj.m*100;
cout << "\n \t In centimeter : " << obj.cm;
}
};
int main ()
{
Convert obj1, obj2;
obj1.input();
obj1.conv_cm(obj1);
obj2.input();
obj2.conv_cm(obj2);
cout << "\n";
return 0;
}

Explanation : In the above example, Inspite of passing data type and


variable in the member function we are passing the class name with
object of that class. In the conv_cm method value of obj.m is passed
by the object passed in the method i.e; Convert.obj.
110

Call by value
Arguments are passed by value, the function create its own copy of
the objects and works with it. Any modification made to the object in
the function does not affect the object used to call the function.
Let us understand passing arguments by value by the following
example more clearly :-
#include <iostream>
using namespace std;
class Convert
{
public :
int i;
void increment(Convert obj)
{
obj.i=obj.i*2;
cout << "Value of i in member function : " << obj.i;
}
};
int main ()
{
Convert obj1;
obj1.i=3;
obj1.increment(obj1);
cout << "\nValue of i in main : " << obj1.i << "\n";
system("pause");
return 0;
}

Explanation : In the output the value of i in member function will be 3 and


in the main function, value is 6, as the copy is created of value of i.
111

Call by reference
If arguments are passed by reference, the memory address is passed
directly to the function. And the function works directly works directly
with the original object.
Let us understand more clearly calling functions by giving reference in
the methods by the following example :-

#include <iostream>
using namespace std;
class Convert
{
public :
int i;
void increment(Convert &obj)
{
obj.i=obj.i*2;
cout << "Value of i in member function : " <<
obj.i;
}
};
int main ()
{
Convert obj1;
obj1.i=3;
obj1.increment(obj1);
cout << "\nValue of i in main : " << obj1.i << "\n";
system("pause");
return 0;
}

Explanation : In the output the value of i in member function will be


6 and in the main function also value is 6, as the address of i is
passed by the & symbol.
112

Constructors & Destructors: Constructors, parameterized


constructors, multiple constructors in a class, constructors with
default arguments, copy constructors, dynamic constructors,
destructors.

Constructors

• A constructor is a special type of member function that


initialises an object automatically when it is created.

• Compiler identifies a given member function is a constructor by


its name and the return type.

• Constructor has the same name as that of the class and it does
not have any return type. Also, the constructor is always public.

class temporary
{
private:
int x;
float y;
public:
// Constructor
temporary(): x(5), y(5.5)
{
// Body of constructor
}
... .. ...
};

int main()
{
Temporary t1;
... .. ...
}

• Above program shows a constructor is defined without a


return type and the same name as the class.

In the above pseudo code, temporary() is a constructor.

When an object of class temporary is created, the constructor is called


automatically, and x is initialized to 5 and y is initialized to 5.5.

You can also initialize the data members inside the constructor's body
as below. However, this method is not preferred.
113

Suppose you are working on 100's of Person objects and the default
value of a data member age is 0. Initialising all objects manually will
be a very tedious task.

Instead, you can define a constructor that initialises age to 0. Then,


all you have to do is create a Person object and the constructor will
automatically initialise the age.

These situations arise frequently while handling array of objects.

Also, if you want to execute some code immediately after an object is


created, you can place the code inside the body of the constructor.

Constructor in detail:

• A class constructor is a special member function of a class that


is executed whenever we create new objects of that class.
• A constructor will have exact same name as the class.
• 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.

Syntax
class_name () { Constructor Definition }

The constructor functions have some special characteristics

• Its name is the same as the class name.


• They should be declared in the public section.
• They are invoked automatically when the objects are created.
• They do not have return types, not even void and therefore, and
they cannot return values.
• They cannot be inherited.
• They can have default arguments.
• Constructors cannot be virtual.
• We cannot refer to their addresses.
• An object with a constructor (or destructor) cannot be used as a
member of a union.
• They make 'implicit calls' to the operators new and delete when
memory allocation is required.
114

Example:
#include <iostream>

class Line
{
public:
void setLength( double len );
double getLength( void );
Line(); // This is the constructor

private:
double length;
};
// Member functions definitions including constructor
Line::Line(void)
{
cout << "Object is being created" << endl;
}
void Line::setLength( double len )
{
length = len;
}
double Line::getLength( void )
{
return length;
}
// Main function for the program
void main( )
{
Line line;
// set line length
line.setLength(6.0);
cout << "Length of line : " << line.getLength() <<endl;
}
OUTPUT:
Object is being created
Length of line : 6
115

Parameterized Constructors

• It may be necessary to initialize the various data elements of


different objects with different values when they are created.
• C++ permits us to achieve this objective by passing arguments
to the constructor function when the objects are created.
• The constructors that can take arguments are
called parameterized constructors.

Example:

class Cube
{
public:
int side;
Cube(int x)
{
side=x;
}
};

int main()
{
Cube c1(10);
Cube c2(20);
Cube c3(30);
cout << c1.side;
cout << c2.side;
cout << c3.side;
}
OUTPUT : 10 20 30

By using parameterized construcor in above case, we have


initialized 3 objects with user defined values. We can have any
number of parameters in a constructor.
116

Example:2
#include <iostream>

class Line
{
public:
void setLength( double len );
double getLength( void );
Line(double len); // This is the constructor
private:
double length;
};
// Member functions definitions including constructor
Line::Line( double len)
{
cout << "Object is being created, length = " << len << endl;
length = len;
}
void Line::setLength( double len )
{
length = len;
}
double Line::getLength( void )

{
return length;
}
// Main function for the program
void main( )
{
Line line(10.0);
// get initially set length.
cout << "Length of line : " << line.getLength() <<endl;
// set line length again
line.setLength(6.0);
cout << "Length of line : " << line.getLength() <<endl;
getch();
}
OUTPUT:
Object is being created, length = 10
Length of line : 10
Length of line : 6
117

Multiple constructors in a class


(Overloading of constructors)

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.

Example1
// Source Code to demonstrate the working of overloaded
constructors
#include <iostream>
using namespace std;

class Area
{
private:
int length;
int breadth;

public:
// Constructor with no arguments
Area(): length(5), breadth(2) { }

// Constructor with two arguments


Area(int l, int b): length(l), 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;
}
};
118

int main()
{
Area A1, 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);

return 0;
}
OUTPUT:

Default Area when no argument is passed.


Area: 10
Area when (2,1) is passed as argument.
Area: 2

For object A1, no argument is passed while creating the object.


Thus, the constructor with no argument is invoked which
initialises length to 5 and breadth to 2. Hence, area of the
object A1 will be 10.
For object A2, 2 and 1 are passed as arguments while creating the
object.
Thus, the constructor with two arguments is invoked which
initialises length to l (2 in this case) and breadth to b (1 in this case).
Hence, area of the object A2 will be 2.
119

Example2:
class Student
{
int rollno;
string name;
public:
Student(int x)
{
rollno=x;
name="None";
}
Student(int x, string str)
{
rollno=x ;
name=str ;
}
};

int main()
{
Student A(10);
Student B(11,"Ram");
}

In above case we have defined two constructors with different


parameters, hence overloading the constructors.
One more important thing, if you define any constructor explicitly,
then the compiler will not provide default constructor and you will
have to define it yourself.
In the above case if we write Student S; in main(), it will lead to a
compile time error, because we haven't defined default constructor,
and compiler will not provide its default constructor because we have
defined other parameterized constructors.
120

Constructors with default arguments


Default constructor is the constructor which doesn't take any argument. It has no
parameter.

Syntax
class_name ()
{ Constructor Definition }

class Cube
{
int side;
public:
Cube()
{
side=10;
}
};

int main()
{
Cube c;
cout << c.side;
}

Output : 10
In this case, as soon as the object is created the constructor is called
which initializes its data members.
A default constructor is so important for initialization of object
members, that even if we do not define a constructor explicitly, the
compiler will provide a default constructor implicitly.
class Cube
{
public:
int side;
};
int main()
{
Cube c;
cout << c.side;
}
121

OUTPUT:
0
In this case, default constructor provided by the compiler will be
called which will initialize the object data members to default value,
that will be 0 in this case.
Copy Constructor

• An object can be initialized with another object of same type.


This is same as copying the contents of a class to another class.

• In the above program, if you want to initialise an object A3 so


that it contains same values as A2, this can be performed as:

....
int main()
{
Area A1, A2(2, 1);

// Copies the content of A2 to A3


Area A3(A2);
OR,
Area A3 = A2;
}

No additional constructor is needed. This is because the copy


constructor is already built into all classes by default.

Copy Constructor is a type of constructor which is used to create a


copy of an already existing object of a class type. It is usually of the
form X (X&), where X is the class name.The compiler provides a
default Copy Constructor to all the classes.

Syntax:
class-name (class-name &)
{
. . . .
}

As it is used to create an object, hence it is called a constructor. And,


it creates a new object, which is exact copy of the existing copy, hence
it is called copy constructor.
122

Copy constructor in detail:

✓ Copy Constructor is a type of constructor which is used to


create a copy of an already existing object of a class type.
✓ The copy constructor is a constructor which creates an
object by initializing it with an object of the same class,
which has been created previously.
✓ The copy constructor is used to:

➢ Initialize one object from another of the same type.


➢ Copy an object to pass it as an argument to a function.
➢ Copy an object to return it from a function.

✓ If a copy constructor is not defined in a class, the compiler


itself defines one.
✓ the class has pointer variables and has some dynamic
memory allocations, then it is a must to have a copy
constructor.
✓ it is usually of the form X (X&), where X is the class name.he
compiler provides a default Copy Constructor to all the
classes.
123

Example:
#include<iostream.h>
#include<conio.h>
class copy
{
int var,fact;
public:
copy(int temp)
{
var = temp;
}
double calculate()
{
fact=1;
for(int i=1;i<=var;i++)
{
fact = fact * i;
}
return fact;
}
};

void main()
{
clrscr();
int n;
cout<<"\n\tEnter the Number : ";
cin>>n;
copy obj(n);
copy cpy=obj;
cout<<"\n\t"<<n<<" Factorial is:"<<obj.calculate();
cout<<"\n\t"<<n<<" Factorial is:"<<cpy.calculate();
getch();
}

OUTPUT:
Im Constructor
Values :10 20
Values :10 20
124

Dynamic Constructors

• Dynamic constructor is used to allocate the memory to the


objects at the run time.
• Memory is allocated at run time with the help of 'new' operator.
• By using this constructor, we can dynamically initialize the
objects.

Example:
#include <iostream.h>
#include <conio.h>
class dyncons
{
int * p;
public:
dyncons()
{
p=new int;
*p=10;
}
dyncons(int v)
{
p=new int;
*p=v;
}
int dis()
{ return(*p);
}
};

void main()
{
clrscr();
dyncons o, o1(9);
cout<<"The value of object o's p is:";
cout<<o.dis();
cout<<"\nThe value of object 01's p is:"<<o1.dis();
getch();
}

The value of object o's p is:10


The value of object 01's p is:9
125

Destructor

➢ Just as objects are created, so are they destroyed. If a class can


have a constructor to set things up, it should also have a
destructor to destruct the object. A destructor, as the name
itself suggests, is used to destroy the objects that have been
created by a constructor. A destructor destroys the values of the
object being destroyed.
➢ A destructor is also a member function whose name is the same
as the class name but is preceded by tilde('~'). For example, the
destructor for the class Sample will bear the name ~Sample().
➢ A destructor takes no arguments, and no return types can be
specified for it (not even void). It is called automatically by the
compiler when an object is destroyed. (A local auto object, local
to a block, is destroyed when the block gets over; a global or
static object is destroyed when the program terminates). A
destructor cleans up the storage (memory area of the object)
that is no longer accessible.
➢ Notice the name of a destructor, it is ~classname(). The symbol
~ refers to a NOT i.e., a destructor is a NOT constructor.

Syntax:

class A
{
public:
~A();
};

Need for Destructors

During construction of an object by the constructor, resources may be


allocated for use.

For example, a constructor may have opened a file and a memory area
may be allotted to it. Similarly, a constructor may have allocated
memory to some other objects.
126

These allocated resources must be deallocated before the object is


destroyed. Now whose responsibility is it ? A destructor volunteers
here for this task and performs all clean-up tasks (like closing a file,
deallocating and releasing memory area) automatically. Therefore, a
destructor is equally useful as a constructor is.

class A
{
A()
{
cout << "Constructor called";
}

~A()
{
cout << "Destructor called";
}
};

int main()
{
A obj1; // Constructor Called
int x=1
if(x)
{
A obj2; // Constructor Called
} // Destructor Called for obj2
} // Destructor called for obj1

Some Characteristics of Destructors

The destructors have some special characteristics associated. These


are :

• Destructor functions are invoked automatically when the


objects are destroyed.
• You can have only one destructor for a class. In other words,
destructors can't be overloaded.
• If a class has a destructor, each object of that class will be de-
initialized before the object goes out of scope. (Local objects at
the end of the block defining them and global and static objects
at the end of the program.)
• Destructor functions also, obey the usual access rules as other
member functions do.
127

• No argument can be provided to a destructor, neither does it


return any value.
• They cannot be inherited.
• A destructor may not be static.
• It is not possible to take the address of a destructor.
• Member functions may be called from within a destructor.
• An object of a class with a destructor cannot be a member of a
union.
128

Notes: Module3
129
130
131

MODULE-IV
Inheritance: Introduction to inheritance, single inheritance, making a
private member inheritable (protected member), multi-level
inheritance, multiple inheritance, hierarchical inheritance, hybrid
inheritance.
Operator Overloading: Rules for overloading operators, overloading
unary operators, overloading binary operators.
Pointers: Introduction to pointers, declaring and initializing pointers,
arithmetic operations on pointers, pointers with arrays, arrays of
pointers, pointers to objects, 'this' pointer.

INHERITANCE:

Inheritance is the capability of one class to acquire properties and


characteristics from another class. The class whose properties are
inherited by other class is called the Parent or Base or Super class.
And, the class which inherits properties of other class is called Child
or Derived or Sub class.

Inheritance makes the code reusable. When we inherit an existing


class, all its methods and fields become available in the new class,
hence code is reused.

NOTE : All members of a class except Private, are inherited

Purpose of Inheritance

1. Code Reusability
2. Method Overriding (Hence, Runtime Polymorphism.)
3. Use of Virtual Keyword

Basic Syntax of Inheritance


class Subclass_name : access_mode Superclass_name

While defining a subclass like this, the super class must be already
defined or atleast declared before the subclass declaration.

Access Mode is used to specify, the mode in which the properties of


superclass will be inherited into subclass, public, privtate or
protected.
132

Example:

Example
class Animal
{ public:
int legs = 4;
};

class Dog : public Animal


{ public:
int tail = 1;
};

int main()
{
Dog d;
cout << d.legs;
cout << d.tail;
}

OUTPUT
41
133

Inheritance Visibility Mode

Depending on Access modifier used while inheritance, the availability


of class members of Super class in the sub class changes. It can
either be private, protected or public.

1) Public Inheritance

This is the most used inheritance mode. In this the protected member
of super class becomes protected members of sub class and public
becomes public.

class Subclass : public Superclass

2) Private Inheritance

In private mode, the protected and public members of super class


become private members of derived class.

class Subclass : Superclass // By default its private inheritance

3) Protected Inheritance

In protected mode, the public and protected members of Super class


becomes protected members of Sub class.

class subclass : protected Superclass

Table showing all the Visibility Modes


Derived Class Derived Class Derived Class

Protected
Base class Public Mode Private Mode
Mode

Private Not Inherited Not Inherited Not Inherited

Protected Protected Private Protected

Public Public Private Protected


134

Types of Inheritance:
C++, we have 5 different types of Inheritance. Namely,

1. Single Inheritance
2. Multiple Inheritance
3. Hierarchical Inheritance
4. Multilevel Inheritance
5. Hybrid Inheritance (also known as Virtual Inheritance)

Single Inheritance

In this type of inheritance one derived class inherits from only one
base class. It is the most simplest form of Inheritance.

Multiple Inheritance

In this type of inheritance a single derived class may inherit from two
or more than two base classes.
135

Hierarchical Inheritance

In this type of inheritance, multiple derived classes inherits from a


single base class.

Multilevel Inheritance

In this type of inheritance the derived class inherits from a class,


which in turn inherits from some other class. The Super class for one,
is sub class for the other.
136

Hybrid (Virtual) Inheritance

Hybrid Inheritance is combination of Hierarchical and Mutilevel


Inheritance.
137
138
139

Multilevel Inheritance
140
141

Multiple Inheritance
142
143

Hierarchical Inheritance
144
145
146

Hybrid Inheritance
147
148
149

Making a private member inheritable (protected


member)
150
151

Syntax of Inheritance in C++


class base_classname
{
properties...
methods...
};
class derived_classname : visibility_mode base_classname
{
properties...
methods...
};
152

Syntax of Hierarchical Inheritance


class base_classname
{
properties;
methods;
};

class derived_class1:visibility_mode base_classname


{
properties;
methods;
};

class derived_class2:visibility_mode base_classname


{
properties;
methods;
};
... ... ...
... ... ...
class derived_classN:visibility_mode base_classname
{
properties;
methods;
};

Syntax of Multilevel Inheritance


class base_classname
{
properties;
methods;
};

class intermediate_classname:visibility_mode base_classname


{
properties;
methods;
};

class child_classname:visibility_mode intermediate_classname


{
properties;
methods;
};
153

Syntax of Multiple Inheritance


class base_class1
{
properties;
methods;
};

class base_class2
{
properties;
methods;
};
... ... ...
... ... ...
class base_classN
{
properties;
methods;
};

class derived_classname : visibility_mode base_class1,


visibility_mode base_class2,... ,visibility_mode base_classN
{
properties;
methods;
};
154

Operator Overloading: Rules for overloading operators, overloading


unary operators, overloading binary operators.

Operator Overloading:

In C++, operators like '+', '-' have specified functions for native data-
types. For example, division operator "/" divides two integers when
used as a / b. But, the functions of these operators can also be
extended for user-defined data-types as well, this is known as
Operator Overloading.

For example:

Suppose we have two objects B and C of class Point containing


integer properties x and y. The two properties represent x and y co-
ordinates of a point respectively. The addition operator "+" can be
overloaded to add the x co-ordinate of B with x co-ordinate of C and
add corresponding y co-ordinates.

Overloading an operator can extend the semantics of an operator but


we can't change its syntax i.e. the grammatical rule that controls its
use such as number of operands, precedence and associativity
remains same. For example, addition operation takes 2 operand,
precedence of division is greater than addition and so on. Operator
overloading is achieved with the help of operator function.

Syntax of Operator Overloading

returntype classname :: operator operator_to_overload ([parameter])


{
statement(s);
... ... ...
}

Operator function must be either friend function or non static member


function. If the operator function is a friend function then it will have
one argument for unary operator and two argument for binary
operator. If the operator function is a non static member function then
it will have no arguments for unary operators and one argument for
binary operators.

Where Operating Overloading is used?

In C++, whatever we can do by overloading an operator can be done


without operator overloading. But operator overloading is used
because it makes program more readable as the operator which are
used for basic data types can also be used for user-defined data
types. For example, consider a program that adds two complex
155

number. To achieve this, we can create a friend function named add()


that adds two complex number and return the result. We can call this
function as,

c = add(c1,c2);

Here, c1 and c2 are two complex number to be added and c holds the
result returned by the function. c, c1 and c2 are objects of a class
complex. Using operator overloading, we can replace the calling
statement as,
c = c1+c2;

This statement gives more sense and user can clearly understand that
two complex numbers are being added. Further statements like
z = add(mult(a,b),sub(x,y));

can be replaced by

z = (a*b)+(x-y);

Rules for operator overloading

1. Only existing member can be overloaded. We can't create our


own operator to overload.
2. The overloaded operator must have at least one operand of user-
defined type.
3. Overloaded operators follow the syntax rules of original
operators. This means we can't change the basic meaning of an
operator.
4. Some operators can't be overloaded. They are: member access
operator (.), pointer to member access operator (.*), scope
resolution operator (::), size operator (sizeof), ternary operator (?
:).
5. We can't use friend function to overload some operators. They
are: assignment operator (=), function call operator (()),
subscripting operator ([]), class member access operator (->).
6. If the operator function is a friend function then it will have one
argument for unary operator and two argument for binary
operator. If the operator function is a non static member
156

function then it will have no arguments for unary operators and


one argument for binary operators.
7. When binary operators are overloaded through member
function, the left hand operand must be an object of the
relevant class.
8. Binary arithmetic operators such as +, -, *, / must explicitly
return a value.

1. C++ program to overload unary minus (-) operator.


#include <iostream>
#include <conio.h>
using namespace std;

class example
{
int a,b;
public:
void input()
{
cout<<"Enter a and b: ";
cin>>a>>b;
}
void operator -() //operator function as a member function
{
a=-a;
b=-b;
}
void display()
{
cout<<"a="<<a<<endl<<"b="<<b<<endl;
}
};

int main()
{
example e;
e.input();
cout<<"Before overloading unary minus operator"<<endl;
e.display();
-e;
cout<<"After overloading unary minus operator"<<endl;
e.display();
getch();
return 0;
}

Enter a and b: 13 -9
Before overloading unary minus operator
a=13
b=-9
After overloading unary minus operator
a=-13
b=9
157

Unary operators:

• Increment (++) Unary operator.


• Decrement (--) Unary operator.
• The minus (-) unary.
• The logical not (!) operator.

#include <iostream>

Example: Operator overloading in C++ Programming

using namespace std;


class Test
{
private:
int count;

public:
Test(): count(5){}

void operator ++()


{
count = count+1;
}
void Display() { cout<<"Count: "<<count; }
};
int main()
{
Test t;
// this calls "function void operator ++()" function
++t;
t.Display();
return 0;
}
Count: 6

This function is called when ++ operator operates on the object of Test


class (object t in this case).

In the program,void operator ++ () operator function is defined (inside


Test class).

This function increments the value of count by 1 for t object.


158
159
160
161
162
163

Pointers: Introduction to pointers, declaring and initializing pointers,


arithmetic operations on pointers, pointers with arrays, arrays of
pointers, pointers to objects, 'this' pointer.

Introduction to pointers

What are Pointers?


A pointer is a variable whose value is the address of another variable.
Like any variable or constant, you must declare a pointer before you
can work with it. The general form of a pointer variable declaration is

type *var-name;

Here, type is the pointer's base type; it must be a valid C++ type and
var-name is the name of the pointer variable. The asterisk you used to
declare a pointer is the same asterisk that you use for multiplication.
However, in this statement the asterisk is being used to designate a
variable as a pointer. Following are the valid pointer declaration −

int *ip; // pointer to an integer


double *dp; // pointer to a double
float *fp; // pointer to a float
char *ch // pointer to character

The actual data type of the value of all pointers, whether integer, float,
character, or otherwise, is the same, a long hexadecimal number that
represents a memory address. The only difference between pointers of
different data types is the data type of the variable or constant that
the pointer points to.
164

Example:
#include <iostream>

using namespace std;

int main () {
int var = 20; // actual variable declaration.
int *ip; // pointer variable

ip = &var; // store address of var in pointer variable

cout << "Value of var variable: ";


cout << var << endl;

// print the address stored in ip pointer variable


cout << "Address stored in ip variable: ";
cout << ip << endl;

// access the value at the address available in pointer


cout << "Value of *ip variable: ";
cout << *ip << endl;

return 0;
}

OUTPUT:
Value of var variable: 20
Address stored in ip variable: 0xbfc601ac
Value of *ip variable: 20
165

Declaring and initializing in pointers

Pointer variables are declared like normal variables except for the
addition of the unary ∗ character.

C++ Pointer Declaration

The general form of a pointer declaration is as follows :

type ∗var_name ;

where type is any valid C++ data type and var_name is the name of
the pointer variable. Following declarations declares pointers of
different types :

int ∗iptr ; //creates an integer pointer iptr


char ∗cptr ; //creates a character pointer cptr
float ∗fptr ; //creates a float pointer fptr

When we say that iptr is an integer pointer, it means that the memory
location being pointer to by iptr can hold only integer values.

In other words, it can stated that iptr is a pointer to integer.

Similarly, in the above given declarations, cptr is a pointer to a


character and fptr is a pointer to a floating-point value.

Thus, it is the base type of the pointer that defines what types of
variables the pointer can point to.

Technically, any type of pointer can point anywhere in memory.

However, all pointer arithmetic is done relative to its base type, so it is


important to declare the pointers correctly.

Two special operators ∗ and & are used with pointers. The & is a
unary operator that returns the memory address of its operand. For
example,

int i = 25 ; // declares an int variable i


int ∗iptr ; // declares an int pointer iptr
iptr = &i ; // stores the memory address of i into iptr
166

The above given assignment statement stores the memory address of i


(& returns memory address of its operand) into iptr so that iptr is now
pointing to the memory location of i.

The expression &i will return an int pointer value because i is an


integer thus, &i will return a pointer to integer.

Similarly, if ch is a character variable, then &ch will return a char


pointer value.

Note - The operand of & operator is as ordinary available but operand


of ∗ is a pointer variable.

Using '∗' operator, changing/accessing value being pointed to by


pointer (its state) is called Dereferencing.

Dereferencing refers to changing/accessing state of the pointer.

The pointer operator ∗ (called "at address" sign) is the same sign as
multiply operator ∗ and the pointer operator & ( called "address of"
sign) is same as bitwise AND operator &. But these operators have no
relationship to each other, Both pointer operator & and ∗ have a
higher precedence than all other arithmetic operators except the
unary minus, with which they have equal precedence.

C++ Pointers Initialization

A pointer variable must not remain uninitialized since uninitialized


pointers cause the system crash. Even if you do not have any legal
pointer value to initialize a pointer, you can initialize it with NULL
pointer value.

Assigning NULL to a pointer initializes it to a value which is not a legal


pointer but it saves you from the 'Big' problem of uninitialized
pointers. A program can later test a pointer against NULL (the zero
pointer) to see whether it contains a legal pointer or not. For example,
consider the following code fragment :

int ∗iptr = NULL ; //iptr gets initialized but does not to a legal
address
:
if(iptr != NULL)
{
: //use the pointer if it pointers to a legal address
}

The expression (iptr != NULL) is equivalent to expression (iptr).


167

The zero pointer NULL is defined in the standard file stddef.h.

When we use NULL for initializing pointers then before using the
pointer anywhere in the program, first check that it is non-zero or
non-NULL as shown in the above code fragment.

#include <iostream>

using namespace std;

int main()

int value = 12;

int *pointer = &value;

cout << "Value lives at: " << value << "\n";

cout << "Pointer lives at: " << *pointer;

cout << "\n\n";

return 0;

The program would produce:

Value lives at: 12

Pointer lives at: 12


168

Arithmetic operation on Pointers

We can't perform multiplication and division on pointers but we can


do addition and subtraction on pointers.

Suppose that p1 is a pointer that points to an integer and the address


is 100 Also assume that an integer occupies 4 bytes. Now if we say:

p1++ ;

what would the above expression do? The value of p1 (i.e. the address
pointed to by p1) gets changed. The address becomes 104 not 101
because an integer occupies 4 bytes. If an integer occupied 2 bytes
then the result would be address 102. Similarly if you do:

p1--;

the address of p1 will be 98.

Hence, when a pointer is incremented it points to the memory location


of the next element of its data type.

Similarly you could say the following:

p1 = p1 + 10;

This makes p1 point to the tenth element of p1's data type beyond the
current position. If p1 points to a character type then p1 + 10 would
move the pointer 10 bytes. Suppose p1 were a integer then p1 would
move 20 bytes (if int occupies 2 bytes).
169
170
171

Pointers and arrays

Pointers are the variables that hold address. Not only can pointers
store address of a single variable, it can also store address of cells of
an array.

Consider this example:

int* ptr;
int a[5];
ptr = &a[2]; // &a[2] is the address of third element of a[5].

Suppose, pointer needs to point to the fourth element of an array, that


is, hold address of fourth array element in above case.

Since ptr points to the third element in the above example, ptr + 1 will
point to the fourth element.

You may think, ptr + 1 gives you the address of next byte to the ptr.
But it's not correct.

This is because pointer ptr is a pointer to an int and size of int is fixed
for a operating system (size of int is 4 byte of 64-bit operating system).
Hence, the address between ptr and ptr + 1 differs by 4 bytes.

If pointer ptr was pointer to char then, the address between ptr and
ptr + 1 would have differed by 1 byte since size of a character is 1
byte.
172

C++ Program to display address of elements of an array using


both array and pointers
#include <iostream>
using namespace std;

int main()
{
float arr[5];
float *ptr;
cout << "Displaying address using arrays: " << endl;
for (int i = 0; i < 5; ++i)
{
cout << "&arr[" << i << "] = " << &arr[i] << endl;
}
// ptr = &arr[0]
ptr = arr;
cout<<"\nDisplaying address using pointers: "<< endl;
for (int i = 0; i < 5; ++i)
{
cout << "ptr + " << i << " = "<< ptr + i << endl;
}
return 0;
}
Displaying address using arrays:
&arr[0] = 0x7fff5fbff880
&arr[1] = 0x7fff5fbff884
&arr[2] = 0x7fff5fbff888
&arr[3] = 0x7fff5fbff88c
&arr[4] = 0x7fff5fbff890

Displaying address using pointers:


ptr + 0 = 0x7fff5fbff880
ptr + 1 = 0x7fff5fbff884
ptr + 2 = 0x7fff5fbff888
ptr + 3 = 0x7fff5fbff88c
ptr + 4 = 0x7fff5fbff890

In the above program, a different pointer ptr is used for displaying the address of
array elements arr. But, array elements can be accessed using pointer notation by
using same array name arr. For example:

int arr[3];

&arr[0] is equivalent to arr


&arr[1] is equivalent to arr + 1
&arr[2] is equivalen to arr + 2
173

Arrays of pointers

We want to maintain an array, which can store pointers to an int or


char or any other data type available. Following is the declaration of
an array of pointers to an integer −

int *ptr[MAX];

This declares ptr as an array of MAX integer pointers. Thus, each


element in ptr, now holds a pointer to an int value. Following example
makes use of three integers which will be stored in an array of
pointers as follows −

#include <iostream>

using namespace std;


const int MAX = 3;

int main () {
int var[MAX] = {10, 100, 200};
int *ptr[MAX];

for (int i = 0; i < MAX; i++) {


ptr[i] = &var[i]; // assign the address of integer.
}

for (int i = 0; i < MAX; i++) {


cout << "Value of var[" << i << "] = ";
cout << *ptr[i] << endl;
}

return 0;
}

Value of var[0] = 10
Value of var[1] = 100
Value of var[2] = 200
174

Pointers to objects
The pointers pointing to objects are referred to as Object Pointers.
class-name ∗ object-pointer ;

where class-name is the name of an already defined class and object-


pointer is the pointer to an object of this class type. For example, to
declare optr as an object pointer of Sample class type, we shall write
Sample ∗optr ;

where Sample is already defined class. When accessing members of a


class using an object pointer, the arrow operator (->) is used instead of
dot operator.
sometimes we don’t know, at the time that we write the program , how
many objects we want to create. when this is the case we can use new
to create objects while the program is running. new returns a pointer
to an unnamed objects.
175

/* C++ Pointers and Objects. Declaration and Use


* of Pointers. This program demonstrates the
* use of pointers in C++ */
#include<iostream.h>
#include<conio.h>
class Time
{
short int hh, mm, ss;
public:
Time()
{
hh = mm = ss = 0;
}
void getdata(int i, int j, int k)
{
hh = i;
mm = j;
ss = k;
}
void prndata(void)
{
cout<<"\nTime is
"<<hh<<":"<<mm<<":"<<ss<<"\n";
}
};
void main()
{
clrscr();
Time T1, *tptr;
cout<<"Initializing data members using the object, with
values 12, 22, 11\n";
T1.getdata(12,22,11);
cout<<"Printing members using the object ";
T1.prndata();
tptr = &T1;
cout<<"Printing members using the object pointer ";
tptr->prndata();
cout<<"\nInitializing data members using the object pointer,
with values 15, 10, 16\n";
tptr->getdata(15, 10, 16);
cout<<"printing members using the object ";
T1.prndata();
cout<<"Printing members using the object pointer ";
tptr->prndata();
getch();
}
176

this pointer
As soon as we define a class, the member functions are created and
placed in the memory space only once.
That is, only one copy of member functions is maintained that is
shared by all the objects of the class.
Only space for data members is allocated separately for each object
(See the following figure).

This has an associated problem.

If only one instance of a member function exists, how does it come to


know which object's data member is to be manipulated ?

For example, if member function 3 is capable of changing the value of


data member2 and we want to change the value of data member2 of
object1.

How could the member function3 come to know which object's data
member2 is to be changed ?

The answer to this problem is this pointer.

When a member function is called, it is automatically passed an


implicit (in-built) argument that is a pointer to the object that invoked
the function.

This pointer is called this. That is if object1 is invoking member


function3, then an implicit argument is passed to member function3
that points to object1 i.e., this pointer now points to object1.
177

The this pointer can be thought of analogous to the ATM card. For
instance, in a bank there are many accounts.

The account holders can withdraw amount or view their bank-


statements through Automatic-Teller-Machines.

Now, these ATMs can withdraw from any account in the bank, but
which account are they supposed to work upon ? This is resolved by
the ATM card, which gives the identification of user and his accounts,
from where the amount is withdrawn.

Similarly, the this pointer is the ATM cards for objects, which
identifies the currently-calling object. The this pointer stores the
address of currently-calling object. To understand this, consider the
following example program (following program illustrates the
functioning of this pointer) :

/* C++ Pointers and Objects. The this pointer.


* This C++ program demonstrates about the this
* pointer in C++ */

#include<iostream.h>
#include<conio.h>
#include<string.h>
class Salesman
{
char name[1200];
float total_sales;
public:
Salesman(char *s, float f)
{
strcpy(name, "");
strcpy(name, s);
total_sales = f;
}
void prnobject(void)
{
cout.write(this->name, 26); // use of
this pointer
cout<<" has invoked prnobject().\n";
}
};
void main()
{
clrscr();
Salesman Rajat("Rajat", 21450), Ravi("Ravi", 23190),
Vikrant("Vikrant", 19142);
/* above statement creates three objects */
Rajat.prnobject();
Vikrant.prnobject();
Ravi.prnobject();
getch();
}
178

Notes:-Module4
179
180
181
182

Module V
Polymorphism and Virtual Functions: Compile-time polymorphism,
runtime polymorphism, virtual functions.
Managing Console I/O Operations: Unformatted I/O operations,
formatted console i/o operations (width( ), precision( ), fill( )),
managing output with manipulators (setw( ), endl).
Templates: Introduction, function templates, class templates.
Exception Handling: Introduction, exception handling mechanism,
throwing mechanism, catching mechanism.

Polymorphism in C++

The process of representing one form in multiple forms is known


as Polymorphism. Here one form represent original form or original
method always resides in base class and multiple forms represents
overridden method which resides in derived classes.
Polymorphism is derived from 2 greek words: poly and morphs. The
word "poly" means many and morphs means forms. So
polymorphism means many forms.

Real life example of Polymorphism in C++

Suppose if you are in class room that time you behave like a
student, when you are in market at that time you behave like a
customer, when you at your home at that time you behave like a
son or daughter, Here one person have different-different behaviors.
183

Type of polymorphism

• Compile time polymorphism

• Run time polymorphism

Compile time Polymorphism Run time Polymorphism


In Compile time Polymorphism, call In Run time Polymorphism, call
is resolved by the compiler. is not resolved by the compiler.
It is also known as Static binding, It is also known as Dynamic
Early binding and overloading as binding, Late
well. binding and overriding as well.
Overloading is compile time Overriding is run time
polymorphism where more than one polymorphism having same method
methods share the same name with with same parameters or signature,
different parameters or signature but associated in a class & its
and different return type. subclass.
It is achieved It is achieved by virtual
by function overloading functions and pointers.
and operatoroverloading.
It provides fast execution because It provides slow execution as
known early at compile time. compare to early binding because it
is known at runtime.
Compile time polymorphism is less Run time polymorphism is more
flexible as all things execute at flexible as all things execute at run
compile time. time.
184

Compile time polymorphism

In C++ programming you can achieve compile time polymorphism


in two way, which is given below;

• Method overloading

• Method overriding

Method Overloading in C++

Whenever same method name is exiting multiple times in the same


class with different number of parameter or different order of
parameters or different types of parameters is known as method
overloading. In below example method "sum()" is present in
Addition class with same name but with different signature or
arguments.
Example of Method Overloading in C++
#include<iostream.h>
#include<conio.h>
class Addition
{
public:
void sum(int a, int b)
{
cout<<a+b;
}
void sum(int a, int b, int c)
{
cout<<a+b+c;
}
};
void main()
{
clrscr();
Addition obj;
obj.sum(10, 20);
cout<<endl;
obj.sum(10, 20, 30);
}
185

Output

30

60

Method Overriding in C++


Define any method in both base class and derived class with same
name, same parameters or signature, this concept is known
as method overriding. In below example same method "show()" is
present in both base and derived class with same name and
signature.
Example of Method Overriding in C++
#include<iostream.h>
#include<conio.h>
class Base
{
public:
void show()
{
cout<<"Base class";
}
};
class Derived:public Base
{
public:
void show()
{
cout<<"Derived Class";
}
}
int mian()
{
Base b; //Base class object
Derived d; //Derived class object
b.show(); //Early Binding Ocuurs
d.show();
getch();
}
186

Output

Base class

Derived Class
187

Virtual Function in C++

A virtual function is a member function of class that is declared


within a base class and re-defined in derived class.
When you want to use same function name in both the base and
derived class, then the function in base class is declared as virtual
by using the virtual keyword and again re-defined this function in
derived class without using virtual keyword.
Syntax

virtual return_type function_name()

.......

.......

}
188

Virtual Function Example


#include<iostream.h>
#include<conio.h>
class A
{
public:
virtual void show()
{
cout<<"Hello base class";
}
};
class B : public A
{
public:
void show()
{
cout<<"Hello derive class";
}
};
void main()
{
clrsct();
A aobj;
B bobj;
A *bptr;
bptr=&aobj;
bptr->show(); // call base class function

bptr=&bobj;
bptr->show(); // call derive class function
getch();
}
Output

Hello base class

Hello derive class


189

Templates

Templates are powerful features of C++ which allows you to write


generic programs. In simple terms, you can create a single function or
a class to work with different data types using templates.

Templates are often used in larger codebase for the purpose of code
reusability and flexibility of the programs.

The concept of templates can be used in two different ways:

• Function Templates
• Class Templates

Function Templates

A function template works in a similar to a normal function, with one


key difference.

A single function template can work with different data types at once
but, a single normal function can only work with one set of data types.

Normally, if you need to perform identical operations on two or more


types of data, you use function overloading to create two functions
with the required function declaration.

However, a better approach would be to use function templates


because you can perform the same task writing less and maintainable
code.

How to declare a function template?

A function template starts with the keyword template followed by


template parameter/s inside < > which is followed by function
declaration.
template <class T>
T someFunction(T arg)
{
... .. ...

In the above code, T is a template argument that accepts different


data types (int, float), and class is a keyword.
190

We can also use keyword typename instead of class in the above


example.

When, an argument of a data type is passed to someFunction( ),


compiler generates a new version of someFunction() for the given data
type.

Example 1: Function Template to find the largest number

Program to display largest among two numbers using function


templates.

#include <iostream>
using namespace std;

// template function
template <class T>
T Large(T n1, T n2)
{
return (n1 > n2) ? n1 : n2;
}

int main()
{
int i1, i2;
float f1, f2;
char c1, c2;

cout << "Enter two integers:\n";


cin >> i1 >> i2;
cout << Large(i1, i2) <<" is larger." << endl;

cout << "\nEnter two floating-point numbers:\n";


cin >> f1 >> f2;
191

cout << Large(f1, f2) <<" is larger." << endl;

cout << "\nEnter two characters:\n";


cin >> c1 >> c2;
cout << Large(c1, c2) << " has larger ASCII value.";

return 0;
}

Output
Enter two integers:
12 13
13 is larger.

Enter two floating-point numbers:


12.03 23.05
23.05 is larger.

Enter two characters:


c
v
v has larger ASCII value.

In the above program, a function template Large() is defined that


accepts two arguments n1 and n2 of data type T. T signifies that
argument can be of any data type.
192

Large() function returns the largest among the two arguments using a
simple conditional operation.

Inside the main() function, variables of three different data


types: int, float and char are declared. The variables are then passed
to the Large() function template as normal functions.

During run-time, when an integer is passed to the template function,


compiler knows it has to generate a Large() function to accept the int
arguments and does so.

Similarly, when floating-point data and char data are passed, it knows
the argument data types and generates the Large() function
accordingly.

This way, using only a single function template replaced three


identical normal functions and made your code maintainable.
193

Example 2: Swap Data Using Function Templates

Program to swap data using function templates.

#include <iostream>
using namespace std;
template <typename T>
void Swap(T &n1, T &n2)
{
T temp;
temp = n1;
n1 = n2;
n2 = temp;
}
int main()
{
int i1 = 1, i2 = 2;
float f1 = 1.1, f2 = 2.2;
char c1 = 'a', c2 = 'b';
cout << "Before passing data to function template.\n";
cout << "i1 = " << i1 << "\ni2 = " << i2;
cout << "\nf1 = " << f1 << "\nf2 = " << f2;
cout << "\nc1 = " << c1 << "\nc2 = " << c2;
Swap(i1, i2);
Swap(f1, f2);
Swap(c1, c2);
cout << "\n\nAfter passing data to function template.\n";
cout << "i1 = " << i1 << "\ni2 = " << i2;
cout << "\nf1 = " << f1 << "\nf2 = " << f2;
cout << "\nc1 = " << c1 << "\nc2 = " << c2;
return 0;
}

Output

Before passing data to function template.

i1 = 1

i2 = 2

f1 = 1.1

f2 = 2.2
194

c1 = a

c2 = b

After passing data to function template.

i1 = 2

i2 = 1

f1 = 2.2

f2 = 1.1

c1 = b

c2 = a

In this program, instead of calling a function by passing a value, a call


by reference is issued.

The Swap() function template takes two arguments and swaps them
by reference.
195

Class Templates

Like function templates, you can also create class templates for
generic class operations.

Sometimes, you need a class implementation that is same for all


classes, only the data types used are different.

Normally, you would need to create a different class for each data type
OR create different member variables and functions within a single
class.

This will unnecessarily bloat your code base and will be hard to
maintain, as a change is one class/function should be performed on
all classes/functions.

However, class templates make it easy to reuse the same code for all
data types.

How to declare a class template?


template <class T>

class className

... .. ...

public:

T var;

T someOperation(T arg);

... .. ...

};

In the above declaration, T is the template argument which is a


placeholder for the data type used.
196

Inside the class body, a member variable var and a member


function someOperation() are both of type T.

How to create a class template object?

To create a class template object, you need to define the data type
inside a < > when creation.

className<dataType> classObject;

For example:

className<int> classObject;
className<float> classObject;
className<string> classObject;
Example 3: Simple calculator using Class template

Program to add, subtract, multiply and divide two numbers using


class template

#include <iostream>
using namespace std;
template <class T>
class Calculator
{
private:
T num1, num2;

public:
Calculator(T n1, T n2)
{
num1 = n1;
num2 = n2;
}

void displayResult()
{
cout << "Numbers are: " << num1 << " and " << num2 <<
"." << endl;
cout << "Addition is: " << add() << endl;
cout << "Subtraction is: " << subtract() << endl;
cout << "Product is: " << multiply() << endl;
cout << "Division is: " << divide() << endl;
}
197

T add() { return num1 + num2; }

T subtract() { return num1 - num2; }

T multiply() { return num1 * num2; }

T divide() { return num1 / num2; }


};

int main()
{
Calculator<int> intCalc(2, 1);
Calculator<float> floatCalc(2.4, 1.2);

cout << "Int results:" << endl;


intCalc.displayResult();

cout << endl << "Float results:" << endl;


floatCalc.displayResult();

return 0;
}

Output

Int results:

Numbers are: 2 and 1.

Addition is: 3

Subtraction is: 1

Product is: 2

Division is: 2

Float results:

Numbers are: 2.4 and 1.2.


198

Addition is: 3.6

Subtraction is: 1.2

Product is: 2.88

Division is: 2

In the above program, a class template Calculator is declared.

The class contains two private members of type T: num1 & num2, and
a constructor to initalize the members.

It also contains public member functions to calculate the addition,


subtraction, multiplication and division of the numbers which return
the value of data type defined by the user. Likewise, a
function displayResult() to display the final output to the screen.

In the main() function,


twodifferent Calculator objects intCalc and floatCalc are created for
data types: int and float respectively. The values are initialized using
the constructor.

Notice we use <int> and <float> while creating the objects. These tell
the compiler the data type used for the class creation.

This creates a class definition each for int and float, which are then
used accordingly.

Then, displayResult() of both objects is called which performs the


Calculator operations and displays the output.
199

Managing Console I/O Operations: Unformatted I/O operations,


formatted console i/o operations (width( ), precision( ), fill( )),
managing output with manipulators (setw( ), endl).

Console input / output function take input from standard input


devices and compute and give output to standard output device.

Generally, keyboard is standard input device and monitor is standard


output device.

In case of C++ it uses streams to perform input and output


operations in standard input output devices (keyboard and
monitor). A stream is an object which can either insert or extract
the character from it.

The standard C++ library is iostream and standard input / output


functions in C++ are:

1. cin
2. cout

There are mainly two types of consol I/O operations form:

1. Unformatted consol input output


2. Formatted consol input output

1) Unformatted consol input output operations

These input / output operations are in unformatted mode. The


following are operations of unformatted consol input / output
operations:

A) void get()

It is a method of cin object used to input a single character from


keyboard. But its main property is that it allows wide spaces and
newline character.

Syntax:

char c=cin.get();
200

#include<iostream>
using namespace std;

int main()
{
char c=cin.get();
cout<<c<<endl;

return 0;
}
K
K

B) void put()

It is a method of cout object and it is used to print the specified character on the
screen or monitor.

Syntax:

cout.put(variable / character);

#include<iostream>
using namespace std;

int main()
{
char c=cin.get();
cout.put(c); //Here it prints the value of variable c;
cout.put('c'); //Here it prints the character 'c';

return 0;
}
I
Ic
201

C) getline(char *buffer,int size)

This is a method of cin object and it is used to input a string with multiple spaces.

Syntax:

char x[30];
cin.getline(x,30);
#include<iostream>
using namespace std;

int main()
{
cout<<"Enter name :";
char c[10];
cin.getline(c,10); //It takes 10 charcters as input;
cout<<c<<endl;

return 0;
}
Enter name :Srinu
Srinu

D) write(char * buffer, int n)

It is a method of cout object. This method is used to read n character from buffer
variable.

Syntax:

cout.write(x,2);
#include<iostream>
using namespace std;

int main()
{
cout<<"Enter name : ";
char c[10];
cin.getline(c,10); //It takes 10 charcters as input;
cout.write(c,9); //It reads only 9 character from buffer c;

return 0;
}

Enter name : Srinivasar


Srinivasa
202

E) cin

It is the method to take input any variable / character / string.

Syntax:
cin>>variable / character / String / ;

#include<iostream>
using namespace std;

int main()
{
int num;
char ch;
string str;

cout<<"Enter Number"<<endl;
cin>>num; //Inputs a variable;
cout<<"Enter Character"<<endl;
cin>>ch; //Inputs a character;
cout<<"Enter String"<<endl;
cin>>str; //Inputs a string;

return 0;
}
Enter Number
07
Enter Character
h
Enter String
Srinu

F) cout

This method is used to print variable / string / character.

Syntax:
cout<< variable / charcter / string;

#include<iostream>
using namespace std;

int main()
{
int num=100;
char ch='X';
string str="Srinu";

cout<<"Number is "<<num<<endl; //Prints value of variable;


cout<<"Character is "<<ch<<endl; //Prints character;
cout<<"String is "<<str<<endl; //Prints string;

return 0;
}
203

Number is 100
Character is X
String is srinu

2) Formatted console input output operations

In formatted console input output operations we uses following


functions to make output in perfect alignment. In industrial
programming all the output should be perfectly formatted due to this
reason C++ provides many function to convert any file into perfect
aligned format. These functions are available in header file <iomanip>.
iomanip refers input output manipulations.

A) width(n)

This function is used to set width of the output.

Syntax:

cout<<setw(int n);

#include<iostream>
#include<iomanip>
using namespace std;

int main()
{
int x=10;
cout<<setw(20)<<variable;

return 0;
}
10
204

B) fill(char)

This function is used to fill specified character at unused space.

Syntax:

cout<<setfill('character')<<variable;
#include<iostream>
#include<iomanip>
using namespace std;

int main()
{
int x=10;
cout<<setw(20);
cout<<setfill('#')<<x;

return 0;
}
##################10

D) precison(n)

This method is used for setting floating point of the output.

Syntax:

cout<<setprecision('int n')<<variable;
#include<iostream>
#include<iomanip>
using namespace std;

int main()
{
float x=10.12345;
cout<<setprecision(5)<<x;

return 0;
}
10.123

E) setflag(arg 1, arg,2)

This function is used for setting format flags for output.

Syntax:

setiosflags(argument 1, argument 2);


205

F) unsetflag(arg 2)

This function is used to reset set flags for output.

Syntax:

resetiosflags(argument 2);

G) setbase(arg)

This function is used to set basefield of the flag.

Syntax:

setbase(argument);
206

Exception Handling in C++

The process of converting system error messages into user friendly


error message is known as Exception handling. This is one of the
powerful feature of C++ to handle run time error and maintain
normal flow of C++ application.

Exception

An exception is an event, which occurs during the execution of a


program, that disrupts the normal flow of the program's
Instructions.

Handling the Exception

Handling the exception is nothing but converting system error


message into user friendly error message. Use Three keywords for
Handling the Exception in C++ Language, they are;

1. try
2. catch
3. throw
207

Syntax for handling the exception


Example of Exception Handling in C++

try

// causes executions code

catch( ExceptionName e1 )

// catch block

catch( ExceptionName e2 )

// catch block

catch( ExceptionName eN )

// catch block

}
208

Try Block

It is one of the block in which we write the block of statements


which causes executions at run time in other words try block
always contains problematic statements.

Catch block

It is one of the block in which we write the block of statements


which will generates user friendly error messages in other words
catch block will suppose system error messages.

Example without Exception Handling

Example
#include<iostream.h>
#include<conio.h>

void main()
{
int a, ans;
a=10;
ans=a/0;
cout<<"Result: "<<ans;
}
Output

Abnormally terminate program


209

Example of Exception Handling

Example
#include<iostream.h>
#include<conio.h>

void main()
{
int a=10, ans=0;
try
{
ans=a/0;
}
catch(int i)
{
cout<<"Denominator not be zero";
}
}
Output

Denominator not be zero

An exception is a problem that arises during the execution of a


program. A C++ exception is a response to an exceptional
circumstance that arises while a program is running, such as an
attempt to divide by zero.

Exceptions provide a way to transfer control from one part of a


program to another. C++ exception handling is built upon three
keywords: try, catch,and throw.

• throw − A program throws an exception when a problem shows


up. This is done using a throw keyword.

• catch − A program catches an exception with an exception


handler at the place in a program where you want to handle
the problem. The catch keyword indicates the catching of an
exception.
210

• try − A try block identifies a block of code for which particular


exceptions will be activated. It's followed by one or more catch
blocks.

Assuming a block will raise an exception, a method catches an


exception using a combination of the try and catch keywords. A
try/catch block is placed around the code that might generate an
exception. Code within a try/catch block is referred to as protected
code, and the syntax for using try/catch as follows −

try {
// protected code
} catch( ExceptionName e1 ) {
// catch block
} catch( ExceptionName e2 ) {
// catch block
} catch( ExceptionName eN ) {
// catch block
}
You can list down multiple catch statements to catch different type
of exceptions in case your try block raises more than one exception
in different situations.

Throwing Exceptions
Exceptions can be thrown anywhere within a code block using throw
statement. The operand of the throw statement determines a type for
the exception and can be any expression and the type of the result of
the expression determines the type of exception thrown.

Following is an example of throwing an exception when dividing by


zero condition occurs −

double division(int a, int b) {


if( b == 0 ) {
throw "Division by zero condition!";
}
return (a/b);
}
211

Catching Exceptions
The catch block following the try block catches any exception. You
can specify what type of exception you want to catch and this is
determined by the exception declaration that appears in parentheses
following the keyword catch.

try {
// protected code
} catch( ExceptionName e ) {
// code to handle ExceptionName exception
}
Above code will catch an exception of ExceptionName type. If you
want to specify that a catch block should handle any type of
exception that is thrown in a try block, you must put an ellipsis, ...,
between the parentheses enclosing the exception declaration as
follows −

try {
// protected code
} catch(...) {
// code to handle any exception
}

C++ Standard Exceptions


C++ provides a list of standard exceptions defined
in <exception> which we can use in our programs. These are
arranged in a parent-child class hierarchy shown below −
212

r.No Exception & Description

1 std::exception

An exception and parent class of all the standard C++ exceptions.

2 std::bad_alloc

This can be thrown by new.

3 std::bad_cast

This can be thrown by dynamic_cast.


213

4 std::bad_exception

This is useful device to handle unexpected exceptions in a C++


program.

5 std::bad_typeid

This can be thrown by typeid.

6 std::logic_error

An exception that theoretically can be detected by reading the code.

7 std::domain_error

This is an exception thrown when a mathematically invalid domain


is used.

8 std::invalid_argument

This is thrown due to invalid arguments.

9 std::length_error

This is thrown when a too big std::string is created.

10 std::out_of_range

This can be thrown by the 'at' method, for example a std::vector


and std::bitset<>::operator[]().

11 std::runtime_error

An exception that theoretically cannot be detected by reading the


code.

12 std::overflow_error
214

This is thrown if a mathematical overflow occurs.

13 std::range_error

This is occurred when you try to store a value which is out of


range.

14 std::underflow_error

This is thrown if a mathematical underflow occurs.


215

Notes:-Module5
216
217
218
219

Das könnte Ihnen auch gefallen