Вы находитесь на странице: 1из 336

OBJECT ORIENTED

PROGRAMMING WITH
C++ (Complete)

Prepared by Deepak Gour


Faculty-Department of IT
Sir Padampat Singhania School of Engineering
C & C++ Differences

C: procedural programming language

z Programming is action-oriented
z Function is basic unit of programming

Deepak Gour, Faculty- Department of IT 2


SPSSE, Udaipur
C & C++ Differences (contd..)
C++: object-oriented programming language
z Programming is object-oriented

z Class (a user-defined data type) is basic unit of


programming
z Attributes (data members)

z Behaviors or operations (member functions)

z Objects are created (instantiated) from the class

z Variables are instances of built-in data types

Deepak Gour, Faculty- Department of IT 3


SPSSE, Udaipur
OO Programming Paradigm
The main features of OO programming are
z Emphasis is on data rather than procedures.
z Programs are divided into OBJECTS.
z Data is hidden and cannot be accessed by
external functions.
z Objects may communicate with each other
through functions.
z New data and functions can be easily added
whenever necessary.
z Follow BOTTOM UP approach in program
design.
Deepak Gour, Faculty- Department of IT 4
SPSSE, Udaipur
Fundamental Concepts in OOP
The main concepts are as follows:
z Objects

z Classes

z Data Abstraction and Encapsulation

z Inheritance

z Polymorphism

z Dynamic binding

z Message passing

Deepak Gour, Faculty- Department of IT 5


SPSSE, Udaipur
What is an Object:
z Definition
z An object is an entity that has
z State (what the object looks like) Class
Members - Attributes
z Behavior (how the object acts) Class
Member Functions

Objects Objects
User
Behaviors State

Deepak Gour, Faculty- Department of IT 6


SPSSE, Udaipur
Example of Object
Object: STUDENT
DATA
Name
Date_of_birth
Marks
----------
FUNCTIONS
Total
Average
----------
Deepak Gour, Faculty- Department of IT 7
SPSSE, Udaipur
CLASS
z Object contain data, and code to
manipulate that data. The entire set of
data and code of an object can be made
a user defined data type with the help of
a CLASS. In fact, objects are variable of
the type CLASS.

z Thus a CLASS is a collection of objects


of similar types.
Deepak Gour, Faculty- Department of IT 8
SPSSE, Udaipur
Class Definition (contd..)
z In C++, a class is declared using the class keyword.
The syntax of a class declaration is similar to that of
a structure. Its general form is,
class class-name {
private:
// private functions and variables
public:
// public functions and variables
} object-list;
In a class declaration the object-list is optional.
Deepak Gour, Faculty- Department of IT 9
SPSSE, Udaipur
Example 1
#include <iostream.h>
using namespace std;
class person
{
private:
char name[30];
int age;
public:
void getdata(void);
void putdata(void);
};
Deepak Gour, Faculty- Department of IT 10
SPSSE, Udaipur
Example 1 (contd..)
void person :: getdata(void)
{
cout << “Enter name: ”;
cin >> name;
cout << “Enter age: ”;
cin >> age;
}

Deepak Gour, Faculty- Department of IT 11


SPSSE, Udaipur
Example 1 (contd..)

void person :: putdata(void)


{
cout << “\n Name: ” << name;
cout << “\n Age: ” << age;
}

Deepak Gour, Faculty- Department of IT 12


SPSSE, Udaipur
Example 1 (contd..)
main ()
{
person p;
p.getdata();
p.putdata();
}

Deepak Gour, Faculty- Department of IT 13


SPSSE, Udaipur
Example 2
#include <iostream.h>
using namespace std;
class item
{
private:
int number;
float cost;
public:
void getdata(int a, float b);
void putdata(void);
};
Deepak Gour, Faculty- Department of IT 14
SPSSE, Udaipur
Example 2 (contd..)
void item :: getdata(void)
{
number = a;
cost = b;
}

Deepak Gour, Faculty- Department of IT 15


SPSSE, Udaipur
Example 2 (contd..)

void item :: putdata(void)


{
cout << “\n Number: ” << number << “\n ”;
cout << “\n Cost: ” << cost << “\n ”;
}

Deepak Gour, Faculty- Department of IT 16


SPSSE, Udaipur
Example 2 (contd..)
main ()
{
item x;
cout << “\n Object x ” << “\n”;
x.getdata(100,175.99);
x.putdata();

item y;
cout << “\n Object y ” << “\n”;
y.getdata(200,285.99);
y.putdata();

}
Deepak Gour, Faculty- Department of IT 17
SPSSE, Udaipur
Class Definition (contd..)
//Fraction abstract data type (ADT) definition
class Fraction{

public: //accessible anywhere in program


Fraction(); //member function prototype
void set(int, int); //member function prototype
void print(); //member function prototype

private: //accessible only to member functions


int num; //data member
int den; //data member

}; //terminate class definition with a semicolon


Deepak Gour, Faculty- Department of IT 18
SPSSE, Udaipur
Member Access Specifiers
z Public
z Any data member or data function declared after
this is accessible anywhere in the program
z Private
z Any data member or data function declared after
this is only accessible to member functions of the
class
z If no specifiers are declared, then the default is
private
z Can list specifiers in any order
z Protected
z Used for inheritance
Deepak Gour, Faculty- Department of IT 19
SPSSE, Udaipur
Member Function Definitions
//Constructor initializes each data member
Fraction::Fraction(){
num = 0;
den = 1;
}
//Set a new Fraction value & check data
void Fraction::set(int n , int d ){
if(d == 0) d = 1;
if(d < 0) {d = -d; n = -n;}
num = n; den = d;
}
//Print a Fraction
void Fraction::print(){
cout << num << " / " << den;
}
Deepak Gour, Faculty- Department of IT 20
SPSSE, Udaipur
Driver Program
// Driver program to test class Fraction
void main(){
//instantiate object t of class Fraction
Fraction t;
t.print(); // 0 / 1

//set the data


t.set( 13, -27);
t.print(); // -13 / 27

//attempt invalid data


t.set( 99, 0);
t.print(); // 99 / 1
}
Deepak Gour, Faculty- Department of IT 21
SPSSE, Udaipur
Accessing Class Members
class Fraction {
public:
Fraction();
void print();
int num, den; //Not good programming practice
};
Fraction::Fraction() {num = 0; den = 1; }
void Fraction::print(){cout<<num<<"/"<<den<<endl;}
void main(){
Fraction t; //instantiate a fraction
Fraction *ptr = &t; //pointer to t
Fraction &ref = t; //reference to t
t.num = 1; t.den = 2; t.print(); // 1/2
ptr->num = 2; ptr->den = 3; ptr->print();// 2/3
ref.num = 3; ref.den = 4; ref.print(); // 3/4
} Deepak Gour, Faculty- Department of IT 22
SPSSE, Udaipur
Accessing Class Members
class Fraction {
Private:
int num, den;
public:
Fraction();
void print();
void setNum(int);
void setDen(int);
int getNum();
int getDen();
};
void Fraction::setNum(int n){num = n;}
void Fraction::setDen(int d){if(d==0)d=1; den = d;}
int Fraction::getNum(){return num;}
int Fraction::getDen(){return den;}
Deepak Gour, Faculty- Department of IT 23
SPSSE, Udaipur
Encapsulation

Objects Objects
User
Behaviors State

Abstraction
Data Hiding
Deepak Gour, Faculty- Department of IT 24
SPSSE, Udaipur
Encapsulation
z Data abstraction allow programmers to hide data
representation details behind a (comparatively)
simple set of operations (an interface)
z What the benefits of data abstraction?
z Reduces conceptual load
z Programmers need to knows less about the rest of the
program
z Provides fault containment
z Bugs are located in independent components
z Provides a significant degree of independence of
program components
z Separate the roles of different programmer

Software
Engineering
Deepak Gour, Faculty- Department of IT 25
Goals SPSSE, Udaipur
Encapsulation (contd..)
z 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 object’s
data and the program.
z This insulation of the data from direct
access by the program is called DATA
HIDING or INFORMATON HIDING.
Deepak Gour, Faculty- Department of IT 26
SPSSE, Udaipur
ABSTRACTION
z ABSTRACTION refers to the act of
representing essential features without
including the background details or
explanations. CLASSES use the concept
of abstraction and are defined as a list of
abstract attributes and functions to
operate on these attributes.

Deepak Gour, Faculty- Department of IT 27


SPSSE, Udaipur
Encapsulation
Classes, Objects and Methods
z The unit of encapsulation in an O-O PL is a class
z An abstract data type

z The set of values is the set of objects (or instances)

z Objects can have a


z Set of instance attributes (has-a relationship)

z Set of instance methods

z Classes can have a Method calls are


z Set of class attributes known as messages
z Set of class methods

z The entire set of methods of an object is known as the


message protocol or the message interface of the
object
Deepak Gour, Faculty- Department of IT 28
SPSSE, Udaipur
Inheritance

Objects Objects
Behaviors State
User
Objects Objects
Behaviors State

Deepak Gour, Faculty- Department of IT 29


SPSSE, Udaipur
Inheritance (contd..)
Inheritance is the process by which objects of one
class acquire the properties of objects of another
class. It supports the concept of hierarchical
classification.
In OOP, the concept of inheritance provides the idea of
reusability. This means that we can add additional
features to an existing class without modifying it.
This is possible by deriving a new class from the
existing one. The new class will have the combined
features of both the classes.
Note that each sub-class defines only those features
that are unique to it. Without the use of
classification, each class would have to explicitly
include all of its features.
Deepak Gour, Faculty- Department of IT 30
SPSSE, Udaipur
POLYMORPHISM

Polymorphism, a Greek term ,means the ability


to take more than one form. An operation may
exhibit different behaviors in different
instances. The behavior depends upon the
type of data used in the operation.
For example, consider the operation of addition.
For two numbers, the operation will generate a
sum. If the operands are strings, then the
operation would produce a third string by
concatenation.
Deepak Gour, Faculty- Department of IT 31
SPSSE, Udaipur
POLYMORPHISM (contd..)
The process of making an operator to exhibit
different behaviors in different instances is
known as operator overloading.
Single function name can be used to handle
different number and different types of
arguments. This is something similar to
particular word having several different
meanings depending on the context.
Using a single function name to perform different
types of tasks is known as function
overloading. Deepak Gour, Faculty- Department of IT 32
SPSSE, Udaipur
POLYMORPHISM (contd..)
Polymorphism plays an important role in
allowing objects having different internal
structures to share the same external
interface. This means that a general
class of operations may be accessed in
the same manner even though specific
actions associated with each operation
may differ. Polymorphism is
extensively used in implementing
Deepak Gour, Faculty- Department of IT 33
inheritance. SPSSE, Udaipur
DYNAMIC BINDING
Binding refers to the linking of a procedure
call to the code to be executed in
response to the call. Dynamic binding
(also known as late binding) means that
the code associated with a given
procedure call is not known until the time
of a 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.
Deepak Gour, Faculty- Department of IT 34
SPSSE, Udaipur
MESSAGE PASSING
An OO program consists of a set of objects
that communicate with each other. The
process of programming in an OOL,
therefore, involves the following basic
steps:
1. Creating classes that defines objects and
their behavior,
2. Creating objects from class definition, and

3. Establishing communication among


objects.
Deepak Gour, Faculty- Department of IT 35
SPSSE, Udaipur
MESSAGE PASSING (contd..)
z 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.

Deepak Gour, Faculty- Department of IT 36


SPSSE, Udaipur
MESSAGE PASSING (contd..)
z A message for an object is a request for
execution of a procedure, and therefore
will invoke a function in the receiving
object that generates the desired result.
Message passing involves specifying the
name of the object, the name of the
function (message) and the information to
be sent.

Deepak Gour, Faculty- Department of IT 37


SPSSE, Udaipur
Applications of C++
C++ is a versatile language for handling
very large programs. It is suitable for
virtually any programming task including
development of editors, compliers,
databases, communication systems and
any complex real-life application systems.

Deepak Gour, Faculty- Department of IT 38


SPSSE, Udaipur
Applications of C++ (contd..)
Applications:
z Since C++ allows us to create hierarchy related objects,
we can build special OO libraries which cane be used
later by many programmers.
z While C++ is able to map the real-world problem
properly, the C part of C++ gives the language the ability
to get close to the machine-level details.
z C++ programs are easily maintainable and expandable.
When a new feature needs to be implemented, it is very
easy to add to the existing structure of an object.
z It is expected that C++ will replace C as a general-
purpose language in the near future.

Deepak Gour, Faculty- Department of IT 39


SPSSE, Udaipur
OUTPUT & INPUT OPERATOR
Output operator
Cout << “C++ is better than C”
This statement introduces two new C++ features,
cout and <<. The operator << is called the
insertion or put to operator.
Input operator
Cin >> number;
This statement introduces two new C++ features,
cin and >>. The operator >> is known as
extraction or get to operator.
Deepak Gour, Faculty- Department of IT 40
SPSSE, Udaipur
Structure of C++ program

Include files
Class declaration
Member functions definitions
Main function program

Deepak Gour, Faculty- Department of IT 41


SPSSE, Udaipur
Constants, Variables, and Data Types
z A programming language is designed to help
process certain kinds of data consisting of
numbers, characters, and strings and to provide
useful output known as information. The task of
processing of data is accomplished by executing
a sequence of precise instructions called a
program. These instructions are formed using
certain symbols and words according to some
rigid rules known as syntax rules (or grammar).
Every program instruction must confirm precisely
to the syntax rules of the language. Like any other
language, C++ has its own vocabulary and
grammar.

Deepak Gour, Faculty- Department of IT 42


SPSSE, Udaipur
CHARACTER SET
z The characters that can be used to form
words, numbers, and expressions
depend upon the computer on which
the program is run. The characters in
C++ are grouped into the following
categories:

Deepak Gour, Faculty- Department of IT 43


SPSSE, Udaipur
CHARACTER SET (contd..)
z Letters
z Digits
z Special characters
z White spaces
The compiler ignores white spaces unless
they are part of a string constant. White
spaces may be used to separate words,
but are prohibited between the
characters of keywords and identifiers.
Deepak Gour, Faculty- Department of IT 44
SPSSE, Udaipur
C TOKENS
z In a passage of text, individual words and
punctuation marks are called tokens.
Similarly, in a C++ program the smallest
individual units are known as C++ tokens.
C++ has six types of tokens as:
z Keywords
z Identifiers
z Constants
z Strings
z Operators
z Special symbols

Deepak Gour, Faculty- Department of IT 45


SPSSE, Udaipur
KEYWORDS & IDENTIFIERS
z Every C++ word is classified as either a
keyword or identifiers. All keywords
have fixed meaning and these meaning
cannot be changed. Keyword serves as
basic building blocks for program
statements. All keywords must be
written in lowercase. Some compilers
may use additional keywords that must
be identified from the C++ manual.
Deepak Gour, Faculty- Department of IT 46
SPSSE, Udaipur
KEYWORDS & IDENTIFIERS (contd..)
z Identifiers refer to the names of variables,
functions and arrays. These are user defined
names and consist of a sequence of letters
and digits, with a letter as a first character.
Both uppercase and lowercase letters are
permitted, although letters are commonly
used. The underscore character is also
permitted in identifiers. It is usually used as a
link between two words in long identifiers.

Deepak Gour, Faculty- Department of IT 47


SPSSE, Udaipur
KEYWORDS & IDENTIFIERS (contd..)
Rules for identifiers:
z First character must be an alphabet (or
underscore).
z Must consist of only letters, digits, or
underscore.
z Only first 31 characters are significant.
z Cannot use a keyword.
z Must not contain white space.
Deepak Gour, Faculty- Department of IT 48
SPSSE, Udaipur
CONSTANTS
z Constants in C++ refer to fixed values
that do not change during the execution
of a program. C++ supports several
types of constants as:
z Numeric Constants i) Integer
Constants ii) Real Constants
z Characters Constants i) Single
Character Constants ii) String
Constants

Deepak Gour, Faculty- Department of IT 49


SPSSE, Udaipur
INTEGER CONSTANT
z An integer constant refers to a
sequence of digits. There are three
types of integers, namely, decimal
integer, octal integer, and hexadecimal
integer.
z Decimal integers consists of a set of
digits, 0 through 9, preceded by an
optional – or + sign.

Deepak Gour, Faculty- Department of IT 50


SPSSE, Udaipur
INTEGER CONSTANT (contd..)
z An octal integer constant consist of any
combination of digits from the set of 0
through 7, with a leading 0.
z A sequence of digits preceded by 0x or
0X is considered as hexadecimal
integers. They may also include
alphabets A through F or a through f.
The letters A through F represent the
numbers 10 through 15.
Deepak Gour, Faculty- Department of IT 51
SPSSE, Udaipur
REAL CONSTANT
z Integer numbers are inadequate to
represent quantities that vary
continuously, such as distances,
heights, etc. These quantities are
represented by numbers containing
fractional parts like 17.548. Such
numbers are called real or floating point
constants.

Deepak Gour, Faculty- Department of IT 52


SPSSE, Udaipur
REAL CONSTANT (contd..)
z A real number may also be expressed in
exponential notations. For example, the
value 215.65 may be written as 2.1565e2
in exponential notation. E2 means
multiply by 102. The general form is:

Mantissa e exponent

Deepak Gour, Faculty- Department of IT 53


SPSSE, Udaipur
REAL CONSTANT (contd..)
z The mantissa is either a real number
expressed in decimal notation or an
integer. The exponent is an integer number
with an optional plus or minus sign. The
letter e separating the mantissa and the
exponent can be written in either
lowercase or uppercase.

Deepak Gour, Faculty- Department of IT 54


SPSSE, Udaipur
SINGLE CHARACTER CONSTANT
z A single character constant contains a
single character enclosed within a pair
of single quote marks. Example is ‘5’,
and ‘x’, ‘ ’
z Note that the character constant ‘5’ is
not having the same value as integer
constant 5. Character constants have
integer value known as ASCII values.

Deepak Gour, Faculty- Department of IT 55


SPSSE, Udaipur
STRING CONSTANT
z A string constant is a sequence of
characters enclosed in double quote.
The characters may be letters,
numbers, special characters and blank
space. Examples are:

“hello”, “1987” etc.

Deepak Gour, Faculty- Department of IT 56


SPSSE, Udaipur
STRING CONSTANT (contd..)
z Remember that a single character
constant is not equivalent to the string
character constant. Further a single
character string constant does not
having any ASCII value as single
character constant.

Deepak Gour, Faculty- Department of IT 57


SPSSE, Udaipur
VARIABLE
z A variable is a data name that may be
used to store a data value. Unlike
constant, a variable may take different
values at different times during
execution.
z Variable name may consist of letters,
digits, and the underscore character,
subject to the following conditions:

Deepak Gour, Faculty- Department of IT 58


SPSSE, Udaipur
VARIABLE (contd..)
z They must begin with a letter. Some systems also
permit underscore as a first character.
z ANSI standard recognizes a length of 31
characters.
z Uppercase and lowercase are significant. That is,
the variable total and TOTAL is not the same.
z It should not be a keyword.
z White space is not allowed.
z Note: only first eight characters are recognized by
a compiler. That means, average_height and
average_weight mean the same thing to the
computer.
Deepak Gour, Faculty- Department of IT 59
SPSSE, Udaipur
DATA TYPES
ANSI C supports three classes of data types
as;
z Primary (or fundamental) data types
(int, char, float, double, void)
z Derived data types (arrays, functions.
pointers, structures)
z User-defined data types

Deepak Gour, Faculty- Department of IT 60


SPSSE, Udaipur
DATA TYPES (contd..)
z All C++ compilers support five
fundamental data types, namely integer
(int), character (char), floating point
(float), double-precision floating point
(double) and void. Many of them also
offer extended data types such as long
int and long double.

Deepak Gour, Faculty- Department of IT 61


SPSSE, Udaipur
INTEGER TYPES
z There are two broader categories as:

Signed Unsigned

Int unsigned int


Short int unsigned Short int
Long int unsigned Long int

Deepak Gour, Faculty- Department of IT 62


SPSSE, Udaipur
CHARACTER TYPES
There are three categories as:

z Char
z Signed characters
z Unsigned characters

Deepak Gour, Faculty- Department of IT 63


SPSSE, Udaipur
FLOATING POINT TYPE
z There are three categories as:

z Float
z Double
z Long double

Deepak Gour, Faculty- Department of IT 64


SPSSE, Udaipur
Table: Size and Range of Data
Types on a 16-bit Machine
Type Size (bits) Range
Char or signed char 8 -128 to 127
Unsigned char 8 0 to 255
Int or signed int 16 -32,768 to 32,767
Unsigned int 16 0 to 65535
Short int or usinsigned short int 8 -128 to 127

Unsigned short int 8 0 to 255


Long int or signed long int 32 -2,147,483,648 to 2,147,483,647

Unsigned long int 32 0 to 4,294,967,295


Float 32 3.4E – 38 to 3.4E + 38
Double 64 1.7E -308 to 1.7E+308
Long double 80 3.4E -4932 to 1.1E+4932
Deepak Gour, Faculty- Department of IT 65
SPSSE, Udaipur
DECLARATION OF VARIABLE
After designing suitable variable names, we
must declare them to compiler.
Declaration does two things:
z It tells the compiler what the variable
name is.
z It specifies what type of data the
variable will hold.
The declaration of the variable must done
before they are used in the program.

Deepak Gour, Faculty- Department of IT 66


SPSSE, Udaipur
PRIMARY TYPE DECLARATION
z A variable can be used to store a value
of any data type. The syntax for
declaring a variable is as follows:
Data-type v1, v2, …. vn;
z v1, v2, ….. vn are the names of the
variables. Variables are separated by
commas. A declaration statement must
end with a semicolon.

Deepak Gour, Faculty- Department of IT 67


SPSSE, Udaipur
Table: Data Type and their
Keywords
Data Type Keyword equivalent
Character Char
Unsigned character Unsigned char
Signed character Signed char
Signed integer Signed int
Signed short integer Signed short int
Signed long integer Signed long int
Unsigned integer Unsigned int
Unsigned short integer Unsigned short int
Unsigned long integer Unsigned long int
Floating point Float
Double precision Floating point Double
Extended double precision Floating point Long double
Deepak Gour, Faculty- Department of IT 68
SPSSE, Udaipur
User-defined Type Declaration
z C++ supports a feature known as “type
definition” that allows users to define
an identifier that would represent and
existing data type. The user defined
data type identifier can later be used to
declare variables. It takes the general
form:
Typedef type identifier;

Deepak Gour, Faculty- Department of IT 69


SPSSE, Udaipur
User-defined Type Declaration
(contd..)
z Where type refers to an existing data type and
identifier refers to the new name given to the
data type. The existing data type may belong
to any class of type, including the user-
defined ones. Remember that the new type is
new only in name, but not the data type.
typedef cannot create a new type.
Examples:
Typedef int units;
Typedef float marks;
Deepak Gour, Faculty- Department of IT 70
SPSSE, Udaipur
User-defined Type Declaration
(contd..)
z Here, units symbolize int and marks
symbolizes float. They can be later used
to declare as follows:

Units batch1;
Marks name1[50];

Deepak Gour, Faculty- Department of IT 71


SPSSE, Udaipur
User-defined Type Declaration
(contd..)
z Another user-defined data type is enumerated
data type provided by ANSI standard. It is
defined as follows:
Enum identifier {value1, value2, ……, valuen};
z The identifier is a user defined data
enumerated data type which can be used to
declare variables that can have one of the
values enclosed within the braces. After this
definition, we can declare variables to be this
new type as below:
Enum identifier V1, v2, ….. vn;
Deepak Gour, Faculty- Department of IT 72
SPSSE, Udaipur
User-defined Type Declaration
(contd..)
z The enumerated variables v1, v2, …, vn
can only have one of the values value 1,
value2, …… valuen. The assignment of
the following types are valid:

V1 = value3;

Deepak Gour, Faculty- Department of IT 73


SPSSE, Udaipur
DECLARATION OF STORAGE
CLASSES
z Variables in C++ can have not only data
type but also storage class that
provides information about their
location and visibility. The storage
class decides the portion of the
program within which the variables are
recognized.

Deepak Gour, Faculty- Department of IT 74


SPSSE, Udaipur
DECLARATION OF STORAGE
CLASSES (contd..)
z The storage variable is another qualifier that
can be added to a variable declaration as
shown below:
Auto int count;
Register char ch;
Static int x;
Extern long total;
z Static and external (extern) variables are
automatically initialized to zero. Automatic
(auto) variables contain undefined values
(known as garbage) unless they are initialized
explicitly.
Deepak Gour, Faculty- Department of IT 75
SPSSE, Udaipur
DECLARATION OF STORAGE
CLASSES (contd..)
Storage Meaning
class
Auto Local variable known only to the function in
which it is declared. Default is auto.

Static Local variable which exists and retains its


value even after the control is transferred to
the calling function.
Extern Global variable known to all functions in the
file.
Register Local variable which is stored in the register.
Deepak Gour, Faculty- Department of IT 76
SPSSE, Udaipur
ASSIGNING THE VALUE TO
VARIABLE
z Values can be assigned to variables
using the assignment operator = as
follows:
Variable_name = constant;
z C permits multiple assignments in one
line. For example
Initial_value = 0; final_value = 100;
are valid statement.

Deepak Gour, Faculty- Department of IT 77


SPSSE, Udaipur
ASSIGNING THE VALUE TO
VARIABLE (contd..)
z An assignment statement implies that
the value of the variable on the left of
the ‘equal sign’ is set equal to the value
of the quantity (or the expression) on
the right.
z During assignment operation, C++
converts the type of value on the right
hand side to the type on the left. This
may involve truncation when real value
is converted into integer.
Deepak Gour, Faculty- Department of IT 78
SPSSE, Udaipur
ASSIGNING THE VALUE TO
VARIABLE (contd..)
z It is also possible to assign a value to a
variable at the time the variable is
declared. This takes the following form:
Data_type variable_name = constant;
z Some examples are:
Int final_value = 100;
Char yes = ‘x’;
Double balance = 100.90;
Deepak Gour, Faculty- Department of IT 79
SPSSE, Udaipur
ASSIGNING THE VALUE TO
VARIABLE (contd..)
z The process of giving initial values to
variable is called initialization. C++
permits the initialization of more than
one variable in one statement using
multiple assignment operators. Some
examples are as follows:
P = q = r = 0;
X = y = z= MAX;

Deepak Gour, Faculty- Department of IT 80


SPSSE, Udaipur
DEFINING SYMBOLIC
CONSTANTS
z Example:

#define STRENGTH 100


#define PASS MARK 50
#define MAX 200
#define PI 3.4159

Deepak Gour, Faculty- Department of IT 81


SPSSE, Udaipur
DEFINING SYMBOLIC
CONSTANTS (contd..)
The following rules apply to #define statement
which defines a symbolic constant:
z Symbolic names have the same form as
variable names.
z No blank space between the pound sign # and
the word define is permitted.
z # must be the first character in the line.
z A blank space is required between #define
and symbolic name and between the symbolic
name and the constant.
z #define statement must not end with a
semicolon.
Deepak Gour, Faculty- Department of IT 82
SPSSE, Udaipur
DEFINING SYMBOLIC
CONSTANTS (contd..)
z After definition, the symbolic name should
not be assigned any value within the program
by using an assignment operator.
z Symbolic names are not declared for data
types. Its data type depends on the type of the
constant.
z #define statement may appear anywhere in
the program but before it is referenced in the
program.

Deepak Gour, Faculty- Department of IT 83


SPSSE, Udaipur
DECLARING A VARIABLE AS
CONSTANT
z We may like the value of certain
variables to remain constant during the
execution of the program. We can
achieve this by declaring the variable
with the qualifier const at the time of
initialization.
z Example:

Const int class_size = 40;

Deepak Gour, Faculty- Department of IT 84


SPSSE, Udaipur
DECLARING A VARIABLE AS
CONSTANT (contd..)
z Const is a new data type qualifier
defined in ANSI. This tells the compiler
that the value of int variable class_size
must not be modified by the program.
However it can be used on the right
hand side of an assignment statement
like any other variable.

Deepak Gour, Faculty- Department of IT 85


SPSSE, Udaipur
DECLARING A VARIABLE AS
VOLATILE
z ANSI standard defines another qualifier
volatile that could be used to tell
explicitly the compiler that a variable’s
value may be changed at any time by
some external source (from outside the
program).
z For example:
Volatile int date;

Deepak Gour, Faculty- Department of IT 86


SPSSE, Udaipur
DECLARING A VARIABLE AS
VOLATILE (contd..)
z The value of date may be altered by
some external factors even if it does not
appear on the left hand side of an
assignment statement. When we
declare an variable as volatile, the
compiler will examine the value of the
variable each time it is encountered to
see whether any external alteration has
changed the value.
Deepak Gour, Faculty- Department of IT 87
SPSSE, Udaipur
OVERFLOW AND UNDERFOW
OF DATA
z Problem of data overflow occurs when
the value of a variable is either too big
or too small for the data type to hold.
The largest value that a variable can
hold also depends on the machine.
Since floating point values are rounded
off to the number of significant digits
allowed, an overflow normally results in
the largest possible real value, whereas
an underflow results in zero.
Deepak Gour, Faculty- Department of IT 88
SPSSE, Udaipur
OPERATORS & EXPRESSIONS
z An operator is a symbol that tells the
computer to perform certain
mathematical or logical manipulations.
Operators are used in programs to
manipulate the data and variables. They
usually form a part of the mathematical
or logical expressions.

Deepak Gour, Faculty- Department of IT 89


SPSSE, Udaipur
OPERATORS & EXPRESSIONS
(contd..)
z C operators can be classified into a number of
categories. They include:
i. Arithmetic operators
ii. Relational operators
iii. Logical operators
iv. Assignment operators
v. Increment and decrement operators
vi. Conditional operators
vii. Bitwise operators
viii. Special operators

Deepak Gour, Faculty- Department of IT 90


SPSSE, Udaipur
TABLE: ARITHMETIC
OPERATORS
Operators Meaning

+ Addition or unary plus

- Subtraction or unary
minus
* Multiplication

/ Division

% Modulo divisions
Deepak Gour, Faculty- Department of IT 91
SPSSE, Udaipur
TABLE: RELATIONAL
OPERATORS
Operators Meaning
< Is less than
<= Is less than or equal to
> Is greater than
>= Is greater than or equal
to
== Is equal to
!= Is not equal to
Deepak Gour, Faculty- Department of IT 92
SPSSE, Udaipur
TABLE: LOGICAL OPERATOR
Operators Meaning

&& Logical AND

|| Logical OR

! Logical NOT

Deepak Gour, Faculty- Department of IT 93


SPSSE, Udaipur
TABLE: SHORTHAND
ASSIGNMENT OPERATOR
Operators Meaning

A=a+1 A+=1

A=a-1 a-=1

A=a*(n+1) A*=n+1

A=a/(n+1) a/=n+1

A=a%b A%=b
Deepak Gour, Faculty- Department of IT 94
SPSSE, Udaipur
INCREMENT & DECREMENT
OPERATORS
Rules for Increment and decrement operators
z Increment and decrement operators are unary
operators and they require variables as their
operands.
z When postfix ++ (or--) is used with a variable in an
expression, the expressions is evaluated first using
the original value of the variable and then the
variable is incremented (or decremented) by one.
z When prefix ++ (or--) is used in an expression, the
variable is incremented (or decremented) first and
then the expression is evaluated using the new
value of the variable.
z The precedence and associatively of ++ and --
operators are the same as those of unary + and
unary -. Deepak Gour, Faculty- Department of IT 95
SPSSE, Udaipur
CONDITIONAL OPERATORS
z A ternary operator pair “? :” is available in C
to construct conditional expressions of the
form
Exp1 ? exp2 : exp3 where exp1, exp2, and
exp3 are expressions.
The operator ? : works as follows:
z Exp1 is evaluated first. If it is nonzero (true),
then the expression exp2 is evaluated and
becomes the value of the expression. If exp1
is false, then exp3 is evaluated becomes the
value of the expression.

Deepak Gour, Faculty- Department of IT 96


SPSSE, Udaipur
TABLE: BITWISE OPERATORS
Operators Meaning

& Bitwise AND

| Bitwise OR

^ Bitwise exclusive OR

<< Shift left

>> Shift right


Deepak Gour, Faculty- Department of IT 97
SPSSE, Udaipur
Dynamic Initialization of
Variables
In C, a variable must be initialized using a
constant expression, and the c compiler
would fix the initialization code at the
time of compilation. C++, however,
permits initialization of the variable at
run time. This is referred to as dynamic
initialization. In C++, a variable can be
initialized at run time using expression
at the place of declaration.

Deepak Gour, Faculty- Department of IT 98


SPSSE, Udaipur
Dynamic Initialization of
Variables (contd..)
For example, the following are valid
initialization statements:

Int n = strlen (string);


Float area = 3.14 * r * r;

Deepak Gour, Faculty- Department of IT 99


SPSSE, Udaipur
Reference Variables
C++ introduces a new kind of variable
known as the reference variable. A
reference variable provides an alias
(alternative name) for the previously
defined variable.
For example, if we make the variable sum a
reference to the variable total, then
sum and total can be used
interchangeably to represent that
variable Deepak Gour, Faculty- Department of IT 100
SPSSE, Udaipur
Reference Variables (contd..)
A reference variable is created as follows:

data-type & reference-name = variable-name;

Example:

float total = 100;


float & sum = total;

Total is a float type variable that has already


been declared; sum is the alternative
declared to represent the variable total. Both
the variable refer to the same data object in
the memory. Deepak Gour, Faculty- Department of IT 101
SPSSE, Udaipur
Reference Variables (contd..)
Now, the statements

cout << total; and


cout << sum; both print the value 100.
The statement
total = total + 10;
will change the value of both total and sum to
110. likewise, the assignment
sum = 0;
will change the value of both the variables to
zero. Deepak Gour, Faculty- Department of IT 102
SPSSE, Udaipur
OPERATPRS IN C++
C++ has a rich set of operators. All C operators are valid
in C++. In addition, introduces some new operators.
The new operators are:
<< the insertion operator
>> the extraction operator
:: scope resolution operator
::* pointer to member declaration
->* pointer to member operator
.* pointer to member operator
delete memory release operator
endl line feed operator
new memory allocation operator
setw field width operator
Deepak Gour, Faculty- Department of IT 103
SPSSE, Udaipur
Scope Resolution Operator
The same variable name can be used
to have different meaning in
different blocks. The scope of the
variable extends from the point of
its declaration till the end of the
block containing the declaration. A
variable declared inside a block is
said to be local to that block.

Deepak Gour, Faculty- Department of IT 104


SPSSE, Udaipur
Scope Resolution Operator (contd..)
The scope resolution operator (::) can be
used to uncover the hidden variable. The
syntax is as follows:
:: variable_name;
This operator allows access to the global
version of variable.
Note: It is to be noted that ::m will always
refer to the global variable

Deepak Gour, Faculty- Department of IT 105


SPSSE, Udaipur
Scope Resolution Operator (contd..)
#include <iostraem>
Int m=10;
Void main()
{
Int m=20;
{
int k=m;
Int m=30;
Cout << “we are in inner block \n”;
Cout << “k= ” << k << “\n”;
Cout << “m= ” << m << “\n”;
Cout << “::m= ” << ::m << “\n”;
}
Cout << “we are in outer block \n”;
Cout << “m= ” << m << “\n”;
Cout << “::m= ” << ::m << “\n”;
Deepak Gour, Faculty- Department of IT 106
} SPSSE, Udaipur
New and Delete Operator
An object can be created by using new,
and destroyed by using delete, as and
when required. A data object created
inside a block with new, will remain in
existence until it is explicitly destroyed
by using delete. Thus the lifetime of an
object is directly under our control and
is unrelated to the block structure of the
program.
Deepak Gour, Faculty- Department of IT 107
SPSSE, Udaipur
New and Delete Operator (contd..)
The new operator can be used to create
objects of any type. The syntax is:

pointer_variable = new data_type;

Here pointer_variable is a pointer of type


data_type. the new operator allocates
sufficient memory to hold a data object of
type data_type and returns the address of
the object.
Deepak Gour, Faculty- Department of IT 108
SPSSE, Udaipur
New and Delete Operator (contd..)
The pointer variable holds the address of
the memory space allocated. For e.g.
p=new int; q=new float;
where p is a pointer of type integer and q
is a pointer of type float. Here p and q
must have already been declared as
pointer of appropriate types. For e.g.
int *p = new int;
int *q = new float;

Deepak Gour, Faculty- Department of IT 109


SPSSE, Udaipur
New and Delete Operator (contd..)
We can also initialize the memory using the new
operator. The syntax is:
pointer_variable = new data_type (value);
int *p = new int(25); float * q = new(10.5);
Here value specifies the initial value.
New can be used to create a memory space of any
data type including user defined data type as
array. The syntax is:
pointer_variable = new data_type [size];
Here size specifies the number of elements in the
array.
Deepak Gour, Faculty- Department of IT 110
SPSSE, Udaipur
New and Delete Operator (contd..)
When a data object is no longer needed, it is
destroyed using delete. The syntax is:

delete pointer_variable;
delete p; delete q;

If we want to free a dynamically allocated array then


the syntax is:

delete [size] pointer_variable; older version


delete [ ] pointer_variable; newer version
Deepak Gour, Faculty- Department of IT 111
SPSSE, Udaipur
New and Delete Operator (contd..)
Advantage of new over malloc()
1. It automatically computes the size of the
data object. We need not use operator
sizeof.
2. It automatically return the correct pointer
type, so there is no need to use a type cast.
3. It is possible to initialize the object while
creating the memory space.
4. New and delete operator can be
overloaded.
Deepak Gour, Faculty- Department of IT 112
SPSSE, Udaipur
MANIPULATORS
Manipulators are operators that are
used to format the data display. The
most commonly used are endl and
setw.
The endl manipulator, when used in an
output, causes a linefeed to be
inserted. It has the same effect as
using the newline characters \n.
Deepak Gour, Faculty- Department of IT 113
SPSSE, Udaipur
MANIPULATORS (contd..)
The setw manipulator right justified the
number. The syntax is:

cout<<setw(width)<<variable_name<< endl;

The manipulator setw specifies the field


width for printing the value of the variable.
The value is also right justified within the
field.
Deepak Gour, Faculty- Department of IT 114
SPSSE, Udaipur
MANIPULATORS (contd..)
#include <iostream>
#include <iomanip>
Void main()
{
int basic=950, allowance=95, total = 1045;
cout<<setw(10)<<“basic”<<setw(10)<<basic<<en
dl<<setw(10)<<“allowance”<<setw(10)<<allowan
ce<<endl<<setw(10)<<“total”<<setw(10)<<
total<<endl;
}
Note: character strings are also printed right
justified.
Deepak Gour, Faculty- Department of IT 115
SPSSE, Udaipur
Special Assignment Expression
Chained Assignment:

x = (y=10); or x = y =10;
A chained statement cannot be used to
initialize a variable at the time of
declaration. For e.g.

float a = b = 12.24; //wrong


float a = 12.24, b=12.24; //right
Deepak Gour, Faculty- Department of IT 116
SPSSE, Udaipur
Special Assignment Expression
Embedded Assignment:

x = (y = 50) + 10; is identical to


y = 50; x = y + 10;

Compound Assignment:

x+=10; is identical to x = x + 10;


Deepak Gour, Faculty- Department of IT 117
SPSSE, Udaipur
Implicit Conversion
We can mix data type in expression. For e.g.
m = 5 + 5.5; is a valid statement. Where
ever data types are mixed, C++ performs
the conversion automatically. This
process is known as implicit or automatic
type conversion.
For e.g. if one of the operand is int and the
other is float, then int is converted into
float because float is wider than int.
Deepak Gour, Faculty- Department of IT 118
SPSSE, Udaipur
FUNCTIONS IN C++
Function Prototyping:
It is a declaration statement in the calling
program and is of the following syntax:
type function_name (argument_list); e.g.
float volume (int x, float y, float z);
Note that each argument must be declared
independently. For e.g.
float volume (int x, float y, z) is illegal.
Deepak Gour, Faculty- Department of IT 119
SPSSE, Udaipur
FUNCTIONS IN C++ (contd..)
In a function declaration, the names of the
arguments are dummy variable and
therefore they are optional. For e.g.
float volume (int, float, float) is legal.
Example program:
float volume (int a, float b, float c)
{
float q = a*b*c;
}
Deepak Gour, Faculty- Department of IT 120
SPSSE, Udaipur
FUNCTIONS IN C++ (contd..)
The function volume() can be invoked as

float cube1 = volume(b1, w1, h1);

The variable b1, w1, and h1 are known as the


actual parameter which specify the
dimension of cube1. Their type should
match with the type declared in prototype.

Deepak Gour, Faculty- Department of IT 121


SPSSE, Udaipur
FUNCTIONS IN C++ (contd..)
Call be reference:
Provision of the reference variable in
C++ permits us to pass parameters
to the functions by reference. When
we pass arguments by reference, the
“formal” arguments in the called
function become aliases to the
“actual” arguments in the calling
function.
Deepak Gour, Faculty- Department of IT 122
SPSSE, Udaipur
FUNCTIONS IN C++ (contd..)
This means that when the function is working with
its own arguments, it is actually working on the
original data. For e.g.
void swap (int &a, int &b)
{
int t=a; // dynamic initialization
a=b; b=t;
}
Now if m and n are two integer variable, then the
function call swap (m, n) will exchange the value
of m and n using their aliases (reference
variable) a and b.
Deepak Gour, Faculty- Department of IT 123
SPSSE, Udaipur
FUNCTIONS IN C++ (contd..)
In traditional C, this is accomplished using
pointers. For e.g.
void swap (int *a, int *b)
{
int t; t=*a; *a=*b; *b=t;
}
The function can be called as swap (&x, &y).
This approach is also acceptable in C++.
Deepak Gour, Faculty- Department of IT 124
SPSSE, Udaipur
FUNCTIONS IN C++ (contd..)
Return by reference:
A function can also return a reference.
For e.g.
int & max (int &x, int &y)
{
if (x>y) return x; else return y;
}
Deepak Gour, Faculty- Department of IT 125
SPSSE, Udaipur
FUNCTIONS IN C++ (contd..)
Since the return type of max() is int &, the
function return reference to x and y (and
not the value). Then the function call such
as max (a, b) will yield a reference to
either a or b depending on their values.
This means that this function appear on
the left hand side of an assignment
statement.
max (a, b) = -1 is legal and assign -1 to a if
it is larger otherwise -1 to b.
Deepak Gour, Faculty- Department of IT 126
SPSSE, Udaipur
FUNCTIONS IN C++ (contd..)
Inline function:
One of the major objective of using function
in a program is to save some memory
space, which becomes appreciable when
a function is likely to be called many
times. However, every time a function is
called, it takes a lot of extra time in
executing a series of instructions for
tasks such as
Deepak Gour, Faculty- Department of IT 127
SPSSE, Udaipur
FUNCTIONS IN C++ (contd..)
1. Jumping to the function
2. Saving registers
3. Pushing arguments to the stack
4. Returning to the calling functions etc

When a function is small, a substantial


percentage of execution time may be spent
in such overhead.
Deepak Gour, Faculty- Department of IT 128
SPSSE, Udaipur
FUNCTIONS IN C++ (contd..)
To eliminate the cost of calls to small
function, C++ proposes a new feature
called Inline function.
An inline function is a function that is
expanded in line when it is invoked. That
is, the compiler replaces the function call
with the corresponding function call.
Syntax is:
inline function_header
{ function_body }
Deepak Gour, Faculty- Department of IT 129
SPSSE, Udaipur
FUNCTIONS IN C++ (contd..)
For e.g.
inline double cube (double a)
{ return (a*a*a); }
function calling:
c = cube (3.0);
d = cube (1.5 _ 2.5);
Usually the function are made inline when
they are small enough to be defined in
one or two lines.
Deepak Gour, Faculty- Department of IT 130
SPSSE, Udaipur
FUNCTIONS IN C++ (contd..)
Note: inline expressions make a
program runs faster because the
overhead of a function call and
return is eliminated. However, it
makes the program to take up more
memory because the statement that
define the inline function are
reproduced at each point where the
function is called.
Deepak Gour, Faculty- Department of IT 131
SPSSE, Udaipur
FUNCTIONS IN C++ (contd..)
Some of the situations where inline
expansions may not work are:

1. For functions returning values, if a loop, a


switch or a goto exists.
2. For function not returning values, if a
return statement exists.
3. If functions contain static variable.
4. If inline functions are recursive.
Deepak Gour, Faculty- Department of IT 132
SPSSE, Udaipur
FUNCTIONS IN C++ (contd..)
Example:
inline float mul (float x, float y)
{ return (x*y); }
inline double div (double p, double q)
{ return (p / q); }
void main ()
{ float a = 12.345; float b = 9.82;
cout<<mul(a,b); cout << div(a,b)}
Deepak Gour, Faculty- Department of IT 133
SPSSE, Udaipur
FUNCTIONS IN C++ (contd..)
Default arguments:
C++ allows us to call a function without
specifying all its arguments. In such cases,
the function assign a default value to the
parameter which does not have a matching
arguments in the function call. Default values
are specified when the function is declared.
The compiler looks at the prototype to see
how many arguments a function uses and
alert the program for possible default values.

Deepak Gour, Faculty- Department of IT 134


SPSSE, Udaipur
FUNCTIONS IN C++ (contd..)

For e.g.
float amount (float p, int t, float r =0.15);
calling
value = amount (5000, 7);
value = amount (5000, 7, 0.12)
Note: only the trailing arguments can have
default values and therefore we must add
defaults from right to left.

Deepak Gour, Faculty- Department of IT 135


SPSSE, Udaipur
FUNCTIONS IN C++ (contd..)
For e.g.

int mul (int i, int j=5, int k=10) //legal


int mul (int i=5, int j) //illegal
int mul (int i=10, int j, int k=5) //illegal
int mul (int i=2, int j=5, int k=10) //legal

Deepak Gour, Faculty- Department of IT 136


SPSSE, Udaipur
FUNCTIONS IN C++ (contd..)
#include <iostream.h>
void main()
{ float amount;
float value (float p, int n, float r=0.15);
void printline (char ch=‘*’, int len=40);
printline();
amount = value (5000.00, 5);
cout<<“\n Final Value =”<<amount;
printline(‘=’);
}

Deepak Gour, Faculty- Department of IT 137


SPSSE, Udaipur
FUNCTIONS IN C++ (contd..)
float value (float p, int n, float r)
{ int year=1; float sum=p;
while (year <=n)
{ sum=sum*(1+r);
year=year+1;
}
return (sum);
}
Deepak Gour, Faculty- Department of IT 138
SPSSE, Udaipur
FUNCTIONS IN C++ (contd..)
void printline (char ch, int len)
{
for (int i=1; i<=len; i++)
cout <<“\n”;
}

Deepak Gour, Faculty- Department of IT 139


SPSSE, Udaipur
FUNCTIONS IN C++ (contd..)
Function Overloading
Overloading refers to the use of the same
thing for different purposes. C++ permits
overloading of the function. This means
that we can use the same function name
to create functions that performs a variety
of different tasks. This is known as
function polymorphism in OOP.

Deepak Gour, Faculty- Department of IT 140


SPSSE, Udaipur
FUNCTIONS IN C++ (contd..)
Using the concept of function overloading,
we can design a family of functions with
one function name but with different
argument lists. The function would
perform different operations depending
on the argument list in the function call.
The correct function to be invoked is
determined by checking the number and
type of the arguments but not on the type.
Deepak Gour, Faculty- Department of IT 141
SPSSE, Udaipur
FUNCTIONS IN C++ (contd..)
For e.g. (Function Declaration)

int add (int a, int b);


int add (int a, int b, int c);
double add (double x, double y);
double add (int p, double q);
double (double p, int q);

Deepak Gour, Faculty- Department of IT 142


SPSSE, Udaipur
FUNCTIONS IN C++ (contd..)
For e.g. (Function call)

cout << add (5,10); //using prototype 1


cout << add(15,10.0); //using prototype 4
cout << add (12.5,7.5); //using prototype 3
cout << add (5,10,15); //using prototype 2
cout << add (0.75, 5); //using prototype 5

Deepak Gour, Faculty- Department of IT 143


SPSSE, Udaipur
FUNCTIONS IN C++ (contd..)
A function call first matches the prototype
having the same number and type of
arguments and then calls the appropriate
function for execution. A best match must
be unique. The function selection involves
the following steps:
1. The compiler first tries to find an exact
match in which the types of actual
arguments are the same.
Deepak Gour, Faculty- Department of IT 144
SPSSE, Udaipur
FUNCTIONS IN C++ (contd..)
2. If an exact match is not found, the
compiler uses the integral promotions
to the actual arguments, such as char
to int and float to double to find a
match.
3. When either of them fails, then compiler
uses the implicit type conversions
mechanism.

Deepak Gour, Faculty- Department of IT 145


SPSSE, Udaipur
FUNCTIONS IN C++ (contd..)
Suppose we use the following two functions:
long square (long);
double square (double);
Then a function call
square (10);
will cause an error due to ambiguity.

4. If all steps fails, then the compiler will try


the user defined conversions.
Deepak Gour, Faculty- Department of IT 146
SPSSE, Udaipur
FUNCTIONS IN C++ (contd..)
Example program of function overloading
#include <iostream>
int volume (int);
double volume (double, int)
long vloume (long, int, int);
void main()
{
cout << volume (10) << endl;
cout << volume (2.5,8) << endl;
cout << volume (100L,75,15) << endl;
}
Deepak Gour, Faculty- Department of IT 147
SPSSE, Udaipur
FUNCTIONS IN C++ (contd..)
int volume (int s) //cube
{ return (s*s*s); }
double volume (double r, int h) //cylinder
{ return (3.14*r*r*h) }
long volume (long l, int b, int h)
//rectangular box
{ return (l*b*h) }

Deepak Gour, Faculty- Department of IT 148


SPSSE, Udaipur
STATIC MEMBER FUNCTION
A member function that is declared static has
the following properties:
1. A static function can have access to only
other static members (functions or
variables) declared in the same class.
2. A static member function can be called
using the class name (instead of its
objects) as follows:
class_name :: function_name;
Deepak Gour, Faculty- Department of IT 149
SPSSE, Udaipur
STATIC MEMBER FUNCTION (contd..)
Example prog. of static member function:
#include <iostream>
class test
{ int code; static int count;
public:
void setcode (void)
{ code = ++count; }
void showcode (void)
{ cout<<“object no.: ”<<code<<endl; }
static void showcount (void)
{ cout<<“count: ” <<count<<endl; }
};
Deepak Gour, Faculty- Department of IT 150
SPSSE, Udaipur
STATIC MEMBER FUNCTION (contd..)
int test :: count;
void main()
{ test t1,t2;
t1.setcode(); t2.setcode();
test :: showcount();
test t3; t3.setcount();
test :: showcount();
t1.showcode();
t2.showcode();
t3.showcode();
}

Deepak Gour, Faculty- Department of IT 151


SPSSE, Udaipur
FRIEND FUNCTION
C++ allows the common function to be
made friendly with more than one classes,
thereby allowing the function to have
access to the private data of these
classes. Such a function need not be a
member of any of these classes.
To make an outside function “friendly” to a
class, we have to simply declare this
function as a friend of the class.
Deepak Gour, Faculty- Department of IT 152
SPSSE, Udaipur
FRIEND FUNCTION (contd..)
class example
{
data members …..
member functions declarations
…….
friend void examplefunc(void);
}

Deepak Gour, Faculty- Department of IT 153


SPSSE, Udaipur
FRIEND FUNCTION (contd..)
The function declaration should be
preceded by the keyword friend. The
function is defined elsewhere in the
program like a normal C++ function. The
function definition does not use either the
keyword friend or scope resolution
operator. A function can be declared as a
friend in any number of classes. A friend
function has full access rights to the
private members of the class.
Deepak Gour, Faculty- Department of IT 154
SPSSE, Udaipur
FRIEND FUNCTION (contd..)
A friend function possesses certain special
characteristics:
1. It is not in the scope of the class to which it
has been declared as friend.
2. Since it is not in the scope of the class, it
cannot be called using the object of that class.
3. It can be invoked like a normal function without
the help of any object.
4. Unlike member functions, it cannot access the
member names directly and has to use an
object name and dot membership operator with
each member name.
Deepak Gour, Faculty- Department of IT 155
SPSSE, Udaipur
FRIEND FUNCTION (contd..)
5. It can be declared either in the public or the
private part of a class without affecting its
meaning.
6. Usually, it has the objects as arguments.

The friend function are often used in operator


overloading.

Deepak Gour, Faculty- Department of IT 156


SPSSE, Udaipur
FRIEND FUNCTION (contd..)
Example of friend function:
class sample
{ private: int a; int b;
public: void setvalue() { a=25; b=40; }
friend float mean (sample s);
};
float mean (sample s)
{ return float (s.a + s.b)/2.0; }

Deepak Gour, Faculty- Department of IT 157


SPSSE, Udaipur
FRIEND FUNCTION (contd..)
void main()
{ sample x;
x.setvalue();
cout << “mean value =” << mean(x);
}

Deepak Gour, Faculty- Department of IT 158


SPSSE, Udaipur
FRIEND FUNCTION (contd..)
Member function of one class can be friend
function of another class. In such cases,
they are defined using the scope
resolution operator as shown below:
class x { int fun(); };
class y { friend int x :: fun(); };
The function fun() is a member of class x
and a friend of class y;

Deepak Gour, Faculty- Department of IT 159


SPSSE, Udaipur
FRIEND FUNCTION (contd..)
We can also declare all the member function
of one class as the friend functions of
another class. In such cases, the class
is called friend class. This can be
specified as follows:

class z { friend class x; };

Deepak Gour, Faculty- Department of IT 160


SPSSE, Udaipur
FRIEND FUNCTION (contd..)
Example of friend class:

class ABC; //forward declaration


class XYZ
{ private: int x;
public: void setvalue(int i) {x=i; }
friend void max (XYZ, ABC);
};

Deepak Gour, Faculty- Department of IT 161


SPSSE, Udaipur
FRIEND FUNCTION (contd..)
class ABC
{ private int a;
public: void setvalue(int i) { a= i; }
friend void max (XYZ, ABC);
};
void max (XYZ m, ABC, n)
{ if (m.x > n.a) cout << m.x;
else cout << n.a;
}

Deepak Gour, Faculty- Department of IT 162


SPSSE, Udaipur
FRIEND FUNCTION (contd..)
void main()
{
ABC abc;
abc.setvalue(10);
XYZ xyz;
xyz.setvalue(20);
max (xyz, abc);
}

Deepak Gour, Faculty- Department of IT 163


SPSSE, Udaipur
CONST MEMBER FUNCTION
If a member function does not alter any data
in the class, then we may declare it as a
const member function as follows:
void mul (int, int) const;
double get_balance () const;
The qualifier const is appended to the
function prototype (in both declaration
and definition). The compiler will generate
an error message if such functions try to
alter the data values;
Deepak Gour, Faculty- Department of IT 164
SPSSE, Udaipur
LOCAL CLASS
Classes can be defined and used inside a
function or a block. Such classes are
called as local classes. Example:

void test (int a)


{ ---- class student { ----};
----- student s1(a);
}

Deepak Gour, Faculty- Department of IT 165


SPSSE, Udaipur
LOCAL CLASS (contd..)
Local classes can use global variables (declared
above the function) and static variables
declared inside the function but cannot use
automatic local variable. The global
variables should be used with the scope
resolution operator.
There are some restrictions in constructing local
classes. They cannot have static data
members and member functions must be
defined inside the local class. Enclosing
function cannot access the private members
of a local class. However, we can achieve
this by declaring the enclosing function as
Deepak Gour, Faculty- Department of IT 166
friend. SPSSE, Udaipur
INHERITANCE
Inheritance between classes

An important feature of classes is the inheritance.


This one allows us to create an object derived
from another one, so that it may include some
of the other's members plus its own ones. For
example, we are going to suppose that we
want to declare a series of classes that
describe polygons like our CRectangle, or like
CTriangle. Both have certain common
features, like for example, the one that both
can be described by means of only two sides:
height and base.
Deepak Gour, Faculty- Department of IT 167
SPSSE, Udaipur
INHERITANCE (contd..)
This could be represented in the world of classes with a
class CPolygon from that we would derive the two
previous ones CRectangle and CTriangle.
The class CPolygon would contain members that are
common for all polygons. In our case: width and
height. And CRectangle and CTriangle would be
its derived classes.
Classes derived from others inherit all the visible members
of the base class. That means that if a base class
includes a member A and we derive it to another
class with another member called B, the derived
class will contain both A and B.

Deepak Gour, Faculty- Department of IT 168


SPSSE, Udaipur
INHERITANCE (contd..)
In order to derive a class from another one, we shall
use the operator : (colon) in the declaration of the
derived class in the following way:
class derived_class_name: public
base_class_name;
where derived_class_name is the name of the derived
class and base_class_name is the name of the
class on which is based. public may be replaced by
anyone of the other access specifiers protected or
private, and describes the access for the inherited
members, as we will see right after this example:
Deepak Gour, Faculty- Department of IT 169
SPSSE, Udaipur
INHERITANCE (contd..)
#include <iostream.h>

class CPolygon {
protected:
int width, height;
public:
void set_values (int a, int b)
{ width=a; height=b;}
};
Deepak Gour, Faculty- Department of IT 170
SPSSE, Udaipur
INHERITANCE (contd..)
class CRectangle: public CPolygon {
public:
int area (void)
{ return (width * height); }
};

class CTriangle: public CPolygon {


public:
int area (void)
{ return (width * height / 2); }
};
Deepak Gour, Faculty- Department of IT 171
SPSSE, Udaipur
INHERITANCE (contd..)
int main () {
CRectangle rect;
CTriangle trgl;
rect.set_values (4,5);
trgl.set_values (4,5);
cout << rect.area() << endl;
cout << trgl.area() << endl;
return 0;
}
20
10
Deepak Gour, Faculty- Department of IT 172
SPSSE, Udaipur
INHERITANCE (contd..)
As you may see, objects of classes CRectangle and
CTriangle contain all of them members of CPolygon,
that are: width, height and set_values().
The protected specifier is similar to private, its only
difference indeed occurs when deriving classes. When
we derive a class, protected members of the base
class can be used by other members of the derived
class, nevertheless private member cannot. As we
wanted that width and height have the ability to be
manipulated by members of its derived classes
CRectangle and CTriangle and not only by members of
CPolygon we have used the protected access instead
of private.
Deepak Gour, Faculty- Department of IT 173
SPSSE, Udaipur
INHERITANCE (contd..)
Access Public Protec Private
ted

members of the same class Yes Yes Yes

members of derived classes Yes Yes No

not-members Yes No No

Deepak Gour, Faculty- Department of IT 174


SPSSE, Udaipur
INHERITANCE (contd..)
In our example, the members inherited by
CRectangle and CTriangle follow with the
same access permission that in the base
class CPolygon:
CPolygon::width // protected access
CRectangle::width // protected access

CPolygon::set_values() // public access


CRectangle::set_values() // public access
Deepak Gour, Faculty- Department of IT 175
SPSSE, Udaipur
INHERITANCE (contd..)
This is because we have derived a class from the
other as public, remember:
class CRectangle: public CPolygon;
this public keyword represents the minimum level of
protection that the inherited members of the base
class (CPolygon) must acquire in the new class
(CRectangle). This minimum access level for the
inherited members can be changed if instead of
public we put protected or private, for example,
suppose that daughter is a class derived from
mother that we defined thus:
class daughter: protected mother;

Deepak Gour, Faculty- Department of IT 176


SPSSE, Udaipur
INHERITANCE (contd..)
this would establish protected as the minimum access
level for the members of daughter that it inherited
from mother. That is, all members that were public
in mother would become protected in daughter,
that would be the minimum level which they can be
inherited. Of course, this would not restrict that
daughter could have its own public members. The
minimum level would only be established for the
inherited members of mother.

Deepak Gour, Faculty- Department of IT 177


SPSSE, Udaipur
TYPES OF INHERITANCE

1. Single Inheritance
2. Multiple Inheritance
3. Hierarchical Inheritance
4. Multilevel Inheritance
5. Hybrid Inheritance

Deepak Gour, Faculty- Department of IT 178


SPSSE, Udaipur
SINGLE INHERITANCE

Deepak Gour, Faculty- Department of IT 179


SPSSE, Udaipur
MULTIPLE INHERITANCE

A B

Deepak Gour, Faculty- Department of IT 180


SPSSE, Udaipur
HIERARCHICAL INHERITANCE

B C D

Deepak Gour, Faculty- Department of IT 181


SPSSE, Udaipur
MULTILEVEL INHERITANCE

Deepak Gour, Faculty- Department of IT 182


SPSSE, Udaipur
HYBRID INHERITANCE
A

B C

Deepak Gour, Faculty- Department of IT 183


SPSSE, Udaipur
SINGLE INHERITANCE
z Example
#include <iostream.h>
class B
{ int a;
public:
int b; void get_ab(); int get_a(void);
void show_a(void);
};
Deepak Gour, Faculty- Department of IT 184
SPSSE, Udaipur
SINGLE INHERITANCE (contd..)
class D : private B
{ int c;
public:
void mul (void);
void display (void);
};

Deepak Gour, Faculty- Department of IT 185


SPSSE, Udaipur
SINGLE INHERITANCE (contd..)
void B :: get_ab (void)
{ cout << “enter the value of a and b:”;
cin >> a >> b;
}
int B :: get_a ()
{ return a; }
void B :: show_a ()
{ cout << “a = ” << a << endl; }
void D :: mul (void)
{ get_ab(); c = b * get_a(); }

Deepak Gour, Faculty- Department of IT 186


SPSSE, Udaipur
SINGLE INHERITANCE (contd..)
void D :: display ()
{ show_a ();
cout << “b = ” << b << endl << “c =” << c; }
int main()
{ D d; d.get_ab(); d.show_a(); d.display();
d.b=20; d.mul(); d.display(); return 0;
}

Deepak Gour, Faculty- Department of IT 187


SPSSE, Udaipur
MULTIPLE INHERITANCE

A class can inherit the attributes of two or


more classes. Multiple inheritance
allows us to combine the features of
several existing classes as a starting
point for defining new classes.

Deepak Gour, Faculty- Department of IT 188


SPSSE, Udaipur
MULTIPLE INHERITANCE (contd..)
#include <iostream.h>
class M
{ protected: int m;
public : void get_m (int);
};
class N
{ protected : int n;
public : void get_n (int);
};
class P : public M, public N
{ public : void display (void); };
void M :: get_m (int x)
{ m = x; }
void N :: get_n (int y)
{ n = y; }
Deepak Gour, Faculty- Department of IT 189
SPSSE, Udaipur
MULTIPLE INHERITANCE (contd..)

void P :: display (void)


{ cout << “m = ” << m << endl;
cout << “n = ” << n << endl;
cout << “m*n = ” << m*n << endl;
}
int main()
{ P p; p.get_m(10); p.get_n(20);
p.display(); return 0;
}
Deepak Gour, Faculty- Department of IT 190
SPSSE, Udaipur
MULTIPLE INHERITANCE (contd..)
We may face a problem in using the multiple
inheritance, when a function with the same name
appears in more than one base class. Consider
the following two classes:
class M
{ public : void display(void)
{cout <<“class M”;}
}
class N
{ public : void display(void)
{cout <<“class N”;}
}
Deepak Gour, Faculty- Department of IT 191
SPSSE, Udaipur
MULTIPLE INHERITANCE (contd..)
Which display() function is used by the derived
class when we inherit these two classes? We
can solve this problem by defining a named
instance within the derived class, using the
class resolution operator with the function as
shown below:
class P : public M, public N
{ public : void display(void)
{M::display();}
};
Deepak Gour, Faculty- Department of IT 192
SPSSE, Udaipur
MULTIPLE INHERITANCE (contd..)
We can now use the derived class as follows:
int main()
{ P p; p.display(); }
Ambiguity may also arise in single inheritance
applications. For instance, consider the following
situations:
class A
{ public : void display() { cout << “A”;} };
class B : public A
{ public : void display() { cout << “B”;} };

Deepak Gour, Faculty- Department of IT 193


SPSSE, Udaipur
MULTILEVEL INHERITANCE
Refer the diagram of Multilevel inheritance.
The class A serves as a base class for the
derived class B, which in turn serves as a
base class for the derived class C. The
class B is known as INTERMEDIATE
BASE class since it provides a link for
the inheritance between A and C. The
chain ABC is known as INHERITANCE
PATH. This process can be extended to
any number of levels.
Deepak Gour, Faculty- Department of IT 194
SPSSE, Udaipur
MULTILEVEL INHERITANCE
#include <iostream.h>
class student
{ protected : int roll_no;
public : void get_no(int);
void put_no(void);
};
void student :: get_no(int a)
{ roll_no = a; }
void student :: put_no()
{ cout << “Roll Number: ” << roll_no; }
Deepak Gour, Faculty- Department of IT 195
SPSSE, Udaipur
MULTILEVEL INHERITANCE
class test : public student
{ protected : float sub1,sub2;
public : void get_marks(float,float);
void put_marks(void);
};
void test :: get_marks(float x,float y)
{ sub1=x; sub2=y; }
void test :: put_marks()
{ cout <<“Marks in Subject 1= ” << sub1;
cout << “Marks in Subject 2= ” << sub2;
}
Deepak Gour, Faculty- Department of IT 196
SPSSE, Udaipur
MULTILEVEL INHERITANCE
class result : public test
{ float total;
public : void display(void);
};
void result :: display(void)
{ total=sub1+sub2;
put_no(); put_marks();
cout << “Total = ” << total;
}

Deepak Gour, Faculty- Department of IT 197


SPSSE, Udaipur
MULTILEVEL INHERITANCE
void main()
{ result student1;
student1.get_no(99);
student1.get_marks(67.5,72.75);
student1.display();
}

Deepak Gour, Faculty- Department of IT 198


SPSSE, Udaipur
HYBRID INHERITANCE
There could be situations where we need to
apply two or more types of inheritance to
design a program. For instance, consider the
case of processing the student results as we
discussed in last example. Assume that we
have to give weightage for sports before
compute the final result. The sports marks
stored in separate class as SPORTS. In this
we have to build new relationship as follows:
Deepak Gour, Faculty- Department of IT 199
SPSSE, Udaipur
HYBRID INHERITANCE (contd..)

student

test sports

result

Deepak Gour, Faculty- Department of IT 200


SPSSE, Udaipur
HYBRID INHERITANCE (contd..)
#include <iostream.h>
class student
{ protected : int roll_no;
public : void get_no(int);
void put_no(void);
};
void student :: get_no(int a)
{ roll_no = a; }
void student :: put_no()
{ cout << “Roll Number: ” << roll_no; }
Deepak Gour, Faculty- Department of IT 201
SPSSE, Udaipur
HYBRID INHERITANCE (contd..)
class test : public student
{ protected : float part1,part2;
public : void get_marks(float,float);
void put_marks(void);
};
void test :: get_marks(float x,float y)
{ part1=x; part2=y; }
void test :: put_marks()
{ cout << “Marks obtained: ” << endl;
cout <<“Part 1= ” << part1; << endl;
cout << “part 2= ” << part2; << endl;
}

Deepak Gour, Faculty- Department of IT 202


SPSSE, Udaipur
HYBRID INHERITANCE (contd..)
class sports
{ protected : score:
public : void get_score(float s)
{score =s;}
void put_score()
{cout <<“sports Wt: ” <<score<< endl;}
};

Deepak Gour, Faculty- Department of IT 203


SPSSE, Udaipur
HYBRID INHERITANCE (contd..)
class result : public test, public sports
{ float total;
public : void display(void);
};
void result :: display(void)
{ total = part1+part2+score;
put_no();
put_marks();
put_score();
cout << “Total Score: ” << total << endl;
}
Deepak Gour, Faculty- Department of IT 204
SPSSE, Udaipur
HYBRID INHERITANCE (contd..)
void main()
{
result student1;
student1.get_no(111);
student1.get_marks(10.5, 14.5);
student1.get_score(9.0);
student1.display();
}
Deepak Gour, Faculty- Department of IT 205
SPSSE, Udaipur
VIRTUAL BASE CLASS
Consider a situation where all the three kinds of
inheritance are involved. This is explained
in next diagram. The CHILD has two direct
base classes as PARENT1 & PARENT2
which themselves have a common base
class GRANDPARENT. The CHILD inherit
the properties of GRANDPARENT via two
separate paths. The GRANDFATHER is
sometimes referred to as indirect base
class.
Deepak Gour, Faculty- Department of IT 206
SPSSE, Udaipur
VIRTUAL BASE CLASS (contd..)

Grandparent

Parent 1 Parent 2

Child

Deepak Gour, Faculty- Department of IT 207


SPSSE, Udaipur
VIRTUAL BASE CLASS (contd..)
Inheritance by the CHILD might pose some
problems. All the public and protected
members of GRANDPARENT are inherited
into CHILD twice, first via PARENT1 and
again via PARENT2. This means CHILD
would have duplicate sets of the members
inherited from GRANDPARENT. This
introduces ambiguity and should be avoided.

Deepak Gour, Faculty- Department of IT 208


SPSSE, Udaipur
VIRTUAL BASE CLASS (contd..)
The duplication of inherited members due to these
multiple paths can be avoided by making the common
base class as virtual base class while declaring the
direct or intermediate base class as shown below:
class GRANDPARENT
{ ------- };
class PARENT1 : virtual public GRANDPARENT
{ --------- };
class PARENT2 : virtual public GRANDPARENT
{ --------- };
class CHILD : public PARENT1, public PARENT2
{ --------- };
Deepak Gour, Faculty- Department of IT 209
SPSSE, Udaipur
VIRTUAL BASE CLASS (contd..)
When a class is made a virtual base class,
C++ takes necessary action to see that
only one copy of that class is inherited,
regardless of how many inheritance paths
exist between the virtual base class and a
derived class.

Deepak Gour, Faculty- Department of IT 210


SPSSE, Udaipur
VIRTUAL BASE CLASS (contd..)
As virtual base class As virtual base class
student

test sports

result

Deepak Gour, Faculty- Department of IT 211


SPSSE, Udaipur
VIRTUAL BASE CLASS (contd..)
#include <iostream.h>
class student
{ protected : int roll_no;
public : void get_no(int);
void put_no(void);
};
void student :: get_no(int a)
{ roll_no = a; }
void student :: put_no()
{ cout << “Roll Number: ” << roll_no; }
Deepak Gour, Faculty- Department of IT 212
SPSSE, Udaipur
VIRTUAL BASE CLASS (contd..)
class test : virtual public student
{ protected : float part1,part2;
public : void get_marks(float,float);
void put_marks(void);
};
void test :: get_marks(float x,float y)
{ part1=x; part2=y; }
void test :: put_marks()
{ cout << “Marks obtained: ” << endl;
cout <<“Part 1= ” << part1; << endl;
cout << “part 2= ” << part2; << endl;
}
Deepak Gour, Faculty- Department of IT 213
SPSSE, Udaipur
VIRTUAL BASE CLASS (contd..)
class sports : public virtual student
{ protected : score:
public : void get_score(float s)
{score =s;}
void put_score()
{cout <<“sports Wt: ” <<score<< endl;}
};

Deepak Gour, Faculty- Department of IT 214


SPSSE, Udaipur
VIRTUAL BASE CLASS (contd..)
class result : public test, public sports
{ float total;
public : void display(void);
};
void result :: display(void)
{ total = part1+part2+score;
put_no();
put_marks();
put_score();
cout << “Total Score: ” << total << endl;
}
Deepak Gour, Faculty- Department of IT 215
SPSSE, Udaipur
VIRTUAL BASE CLASS (contd..)
void main()
{
result student1;
student1.get_no(111);
student1.get_marks(10.5, 14.5);
student1.get_score(9.0);
student1.display();
}
Deepak Gour, Faculty- Department of IT 216
SPSSE, Udaipur
ABSTRACT CLASSES
An abstract class is one that is not
used to create objects. An abstract
class is designed only to act as a
base class (to be inherited by other
classes). It is a design concept in
program development and provides
a base upon which other classes
may be built.
Deepak Gour, Faculty- Department of IT 217
SPSSE, Udaipur
CONSTRUCTORS
As long as no base class constructor
takes any arguments, the derived
class need not have a constructor
function. However, if any base class
contains a constructor with one or more
arguments, then it is mandatory for the
derived class to have a constructor and
pass the arguments to the base class
constructor. Deepak Gour, Faculty- Department of IT 218
SPSSE, Udaipur
CONSTRUCTORS (contd..)
When both the derived and base classes
contain constructors, the base constructor
is executed first and then the constructor in
the derived class is executed.
In case of multiple inheritance, the base
classes are constructed in the order in
which they appear in the declaration of
the derived class. Similarly, in a multilevel
inheritance, the constructors will be
executed in the order of inheritance.
Deepak Gour, Faculty- Department of IT 219
SPSSE, Udaipur
CONSTRUCTORS (contd..)

The constructors for virtual base


classes are invoked before any
non-virtual base classes. If there
are multiple virtual base classes,
they are invoked in the order in
which they are declared.

Deepak Gour, Faculty- Department of IT 220


SPSSE, Udaipur
CONSTRUCTORS (contd..)
Method of inheritance Order of execution
Class B : public A { }; A(); base constructor
B(); derived constructor
Class A : public B, public B(); base (first)
C { }; C(); base (second)
A(); derived
Class A : public B, virtual C(); virtual base
public C { }; B(); ordinary base
A(); derived

Deepak Gour, Faculty- Department of IT 221


SPSSE, Udaipur
CONSTRUCTORS (contd..)
#include <iostream.h>
class alpha
{ int x;
public :
alpha(int i)
{x=i; cout << “alpha initialized” << endl; }
void show_x(void)
{ cout << “x= ” << x << endl; }
};

Deepak Gour, Faculty- Department of IT 222


SPSSE, Udaipur
CONSTRUCTORS (contd..)
class beta
{ float y;
public :
beta (float j)
{ y=j; cout << beta initialized” << endl; }
void show_y(void)
{ cout << “Y = ” << y << endl; }
};

Deepak Gour, Faculty- Department of IT 223


SPSSE, Udaipur
CONSTRUCTORS (contd..)
class gamma : public beta, public alpha
{ int m,n;
public :
gamma(int a, float b, int c, int d) : alpha(a),beta(b)
{ m=c; n=d; cout << “gamma initialized” << endl; }
void show_mn(void)
{ cout << “M = ” << m << endl;
cout << “N = ” << n << endl; }
};
Deepak Gour, Faculty- Department of IT 224
SPSSE, Udaipur
CONSTRUCTORS (contd..)
void main()
{
gamma g(5, 10, 15, 20);
g.show_x();
g.show_y();
g.show_mn();
}

Deepak Gour, Faculty- Department of IT 225


SPSSE, Udaipur
OPERATOR OVERLOADING
The mechanism of giving such special
meanings to an operator is known as
operator overloading.
Operator overloading provides a flexible
option for the creation of new
definitions for most of the C++
operators.
Deepak Gour, Faculty- Department of IT 226
SPSSE, Udaipur
OPERATOR OVERLOADING (contd..)

We can overload all the C++ operators except


the following:

1. Class member access operators (.,.*)


2. Scope resolution operator (::)
3. Size operator (sizeof)
4. Conditional operator (?:)

Deepak Gour, Faculty- Department of IT 227


SPSSE, Udaipur
OPERATOR OVERLOADING (contd..)
Although the semantics of an operator
can be extended, we cannot change its
syntax. When an operator is overloaded,
its original meaning is not lost. For
instance, the operator +, which has
been overloaded to add two vectors,
can still be used to add two integers.

Deepak Gour, Faculty- Department of IT 228


SPSSE, Udaipur
OPERATOR OVERLOADING (contd..)

To define an additional task to an operator,


we must specify what it means in relation to
the class to which the operator is applied.
This is done with the help of a special
function, called operator function, which
describes the task. The general form is:

return type class name :: operator op (arg. list)


{
function body
}
Deepak Gour, Faculty- Department of IT 229
SPSSE, Udaipur
OPERATOR OVERLOADING (contd..)

where return type is the type of value returned by


the specified operation and op is the operator being
overload. The op is preceded by the keyword
operator.
Operator functions must be either member functions
(non static) or friend functions. A basic difference
between them is that a friend function will only have
one argument for unary operator and two for binary
operators, while a member function has no
arguments for unary operator and only one for
binary operator.

Deepak Gour, Faculty- Department of IT 230


SPSSE, Udaipur
OPERATOR OVERLOADING (contd..)
The process of overloading involves the
following steps:
1. Create a class that defines the data type that
is to be used in the overloading operation.
2. Declare the operator function operator op() in
the public part of the class. It may be either a
member function or a friend function.
3. Define the operator function to implement the
required operations.

Deepak Gour, Faculty- Department of IT 231


SPSSE, Udaipur
OPERATOR OVERLOADING (contd..)
Overloading unary operator (unary subtraction)

#include <iostream.h>
class space
{ int x,y,z;
public:
void getdata(int a, int b, int c);
void display(void);
void operator -- ();
};
Deepak Gour, Faculty- Department of IT 232
SPSSE, Udaipur
OPERATOR OVERLOADING (contd..)

void space :: getdata(int a, int b, int c)


{ x=a; y=b; z=c; }

void space :: display(void)


{ cout << x << “ ” << y << “ ” << z; }

void space operator -- ()


{ x= -x; y = - y; z = -z; }

Deepak Gour, Faculty- Department of IT 233


SPSSE, Udaipur
OPERATOR OVERLOADING (contd..)
void main()
{ space S;
S.getdata(1,2,-3);
cout << “S : ”;
S.display();
--S;
cout << “S : ”;
S.display();
}
Deepak Gour, Faculty- Department of IT 234
SPSSE, Udaipur
OPERATOR OVERLOADING (contd..)

It is possible to overload a unary minus


operator using a friend function as follows:
friend void operator -- (space &s); //declaration
void operator -- (space &s) //definition
{
s.x = -- s.x; s.y = -- s.y; s.z = -- s.z;
}

Deepak Gour, Faculty- Department of IT 235


SPSSE, Udaipur
OPERATOR OVERLOADING (contd..)

NOTE: The arguments is passed by


reference. It will not work if we pass
argument by value because only a copy of
the object that activated the call is passed
to operator --(). Therefore the changes
made inside the operator function will not
reflect in the called object.

Deepak Gour, Faculty- Department of IT 236


SPSSE, Udaipur
OPERATOR OVERLOADING (contd..)
Overloading binary operator
#include<iostream.h>
class complex
{ float x, float y;
public:
complex() { }
complex(float real, float imag)
{x=real;y=imag;}
complex operator +(complex);
void display (void);
}

Deepak Gour, Faculty- Department of IT 237


SPSSE, Udaipur
OPERATOR OVERLOADING (contd..)
complex complex :: operator +(complex c)
{ complex temp; temp.x=x+c.x; temp.y = y+c.y;
return (temp); }
void complex :: display (void)
{ cout << x << “+ j” << y << endl; }
void main()
{ complex C1,C2,C3;
C1=complex(2.5,3.5);
C2=complex(1.6,2.7);
C3=C1+C2;
cout << “C1: ” ; C1.display();
cout << “C2: ” ; C2.display();
cout << “C3: ” ; C3.display();
}
Deepak Gour, Faculty- Department of IT 238
SPSSE, Udaipur
OPERATOR OVERLOADING (contd..)
Note the following features of the operator +
function:
1. It receives only one complex type
arguments explicitly.
2. It returns a complex data type.
3. It is a member function of complex.
As a rule, in overloading of binary operators,
the left hand operand is used to invoke the
operator function and the right hand
operand is passed as an arguments.
Deepak Gour, Faculty- Department of IT 239
SPSSE, Udaipur
OPERATOR OVERLOADING (contd..)
The complex number program discussed earlier
can be modified using a friend operator
function as follows:
1. Replace the member function declaration by
the friend function declaration.
friend complex operator+(complex a, complex b)
2. Redefine the operator function as follows:
complex operator +(complex a, complex b)
{return complex ((a.x+b.x),(a.y+b.y))};
Deepak Gour, Faculty- Department of IT 240
SPSSE, Udaipur
OPERATOR OVERLOADING (contd..)
In this case, the statement
C3=C1+C2; is equivalent to
C3=operator+(C1,C2);

Deepak Gour, Faculty- Department of IT 241


SPSSE, Udaipur
OPERATOR OVERLOADING (contd..)
#include <iostream.h>
class distance
{
private: int feet; float inches;
public: distance () : feet(0),inches(0.0) { }
distance (int ft, float in) : feet(ft) , inches(in) { }

void getdist()
{ cout << “Enter feet: ”; cin >> feet;
cout << “Enter inches: ” ; cin >> inches; }
Deepak Gour, Faculty- Department of IT 242
SPSSE, Udaipur
OPERATOR OVERLOADING (contd..)
void showdist()
{ cout << feet << “ ” << inches; }
distance operator + (distance);
};
distance distance:: operator + (distance d2)
{int f = feet + d2.feet; float i = inches + d2.inches;
if (i >= 12.0) {i-=12.0; f++; } return distance(f,i);
}
Deepak Gour, Faculty- Department of IT 243
SPSSE, Udaipur
OPERATOR OVERLOADING (contd..)
void main()

{ distance dist1, dist3, dist4; dist1.getdata();


distance dist2(11,6.25); dist3 = dist1 + dist2;
dist4 = dist1 + dist2 + dist3;
cout << “dist1 = ”; dist1.showdist(); cout << endl;
cout << “dist2 = ”; dist2.showdist(); cout << endl;
cout << “dist3 = ”; dist3.showdist(); cout << endl;
cout << “dist4 = ”; dist4.showdist(); cout << endl;
}

Deepak Gour, Faculty- Department of IT 244


SPSSE, Udaipur
OPERATOR OVERLOADING (contd..)
Mathematical operations on strings
#include <string.h>
#include <iostream.h>
class string
{ char *p; int len;
public:
string () {len=0;p=0;} //create null string
string (const char *s);//create string from
array
string (const string &s);//copy const.
~string () {delete p;} //destructor

Deepak Gour, Faculty- Department of IT 245


SPSSE, Udaipur
OPERATOR OVERLOADING (contd..)
friend string operator + (const string &s,
const string &t); //+ operator
friend int operator <= (const string &s,
const string &t); //<= operator
friend void show (const string s);
};
string :: string (const char *s)
{ len = strlen(s); p = new char [len+1];
strcpy(p,s) }

Deepak Gour, Faculty- Department of IT 246


SPSSE, Udaipur
OPERATOR OVERLOADING (contd..)
string :: string (const string & s)
{ len = s.len; p = new char[len+1];
strcpy(p,s.p); }
string operator + (const string &s, const
string &t)
{ string temp; temp.len=s.len+t.len;
temp.p=new char[temp.len+1];
strcpy(temp.p, s.p); strcat( temp.p, t.p);
return (temp);
}
Deepak Gour, Faculty- Department of IT 247
SPSSE, Udaipur
OPERATOR OVERLOADING (contd..)
int operator <= (const string &s, const
string &t)
{ int m = strlen (s.p); int n = strlen (t.p);
if (m<=n) return (1); else return (0);
}
void show (const string s)
{ cout << s.p; }

Deepak Gour, Faculty- Department of IT 248


SPSSE, Udaipur
OPERATOR OVERLOADING (contd..)
void main()
{ string s1 = “Mumbai”;
string s2 =“Delhi”;
string s3 = “Udaipur”;
string t1, t2, t3;
t1=s1; t2=s2; t3=t1+t2;
cout << show(t1); cout <<show (t2);
cout << show (t3);
if (t1<=t3) show (t1);else show (t3);
}

Deepak Gour, Faculty- Department of IT 249


SPSSE, Udaipur
OPERATOR OVERLOADING (contd..)
Rules for operator overloading:

1. Only existing operators can be overloaded. New operator


cannot be created.
2. The overloaded operator must have at least one operand that
is of user defined type.
3. We cannot change the basic meaning of any operator.
4. Overloaded operators follow the syntax rules of the original
operators. They cannot be overridden.
5. There are some operators that cannot be overloaded.
6. We cannot use friend function to overload certain operators.
7. When using binary operators overloaded through a member
function, the left hand operand must be an object of the
relevant class.
8. Binary arithmetic operators must explicit return a value.
Deepak Gour, Faculty- Department of IT 250
SPSSE, Udaipur
Pointers
z A pointer is just the memory address of a
variable, so that a pointer variable is just a
variable in which we can store different
memory addresses. Pointer variables are
declared using a "*", and have data types like
the other variables we have seen. For
example, the declaration
int *number_ptr;
states that "number_ptr" is a pointer variable
that can store addresses of variables of data
type "int". A useful alternative way to declare
pointers is using a "typedef" construct.
Deepak Gour, Faculty- Department of IT 251
SPSSE, Udaipur
Pointers (contd..)
z For example, if we include the
statement:
typedef int *IntPtrType;
we can then go on to declare several
pointer variables in one line, without
the need to prefix each with a "*":
IntPtrType number_ptr1,
number_ptr2, number_ptr3;

Deepak Gour, Faculty- Department of IT 252


SPSSE, Udaipur
Pointers (contd..)
Manipulation of pointers;
We can manipulate a pointer with the
indirection operator ‘*’, which is also known
as deference operator. With this operator,
we can indirectly access the data variable
content. It takes the following general form:

*pointer_variable;

Deepak Gour, Faculty- Department of IT 253


SPSSE, Udaipur
Pointers (contd..)
#include <iostream.h>
#include <conio.h>
void main ()
{ int a = 10, *ptr;
ptr=&a; clrscr();
cout << “the value of a is: ” << a;
*ptr = (*ptr)/2;
cout << “The value of a is: ” << (*ptr);
} //check the output
Deepak Gour, Faculty- Department of IT 254
SPSSE, Udaipur
Pointers (contd..)
Pointer expressions and pointer arithmetic:

z A pointer can be incremented or


decremented.
z Any integer can be added or subtracted
from a pointer.
z One pointer can be subtracted from
another.
Deepak Gour, Faculty- Department of IT 255
SPSSE, Udaipur
Pointers (contd..)
Example:
#include <iostream.h>
#include <conio.h>
void main()
{ int num[] = {1,2,3,4,5};
int *ptr; int i; clrscr();
cout << “The array values are: ”;
for (i=0; i<5;i++) cout << num[i];
ptr = num;
cout << “Value of ptr: ” << *ptr;

Deepak Gour, Faculty- Department of IT 256


SPSSE, Udaipur
Pointers (contd..)
cout << “Value of ptr++” << *ptr;
ptr--;
cout << “Value of ptr--” << *ptr;
ptr=ptr+2;
cout << “Value of ptr+2” << *ptr;
ptr=ptr-1;
cout << “Value of ptr-1” << *ptr;
ptr+=3;
cout << “Value of ptr+3” << *ptr;
ptr-=2;
cout << “Value of ptr+2” << *ptr;
}

Deepak Gour, Faculty- Department of IT 257


SPSSE, Udaipur
Pointers with Arrays & Strings
Pointers is one of the efficient tools to access
elements of an array. Pointers are useful to
allocate array dynamically, i.e. we can decide
the array size at run time. For this, we use the
function malloc() and calloc().
We can declare the pointers to arrays as follows:
int *nptr;
nptr = number[0]; or nptr = number;
Here nptr points to the first element of the integer
array.
Deepak Gour, Faculty- Department of IT 258
SPSSE, Udaipur
Pointers with Arrays & Strings
#include <iostream.h>
void main()
{int number[50], *ptr;
int n,i;
cout << “enter the count”; cin >> n;
cout <<“enter the number one by one”;
for (i=0;i<n;i++)
cin >> number[i];
Deepak Gour, Faculty- Department of IT 259
SPSSE, Udaipur
Pointers with Arrays & Strings
ptr=number;
int sum=0;
for (i=0;i<n;i++)
{ if (*ptr%2==0)
sum=sum+*ptr;
ptr++;
}
cout << “sum of even numbers” << sum;
}
Deepak Gour, Faculty- Department of IT 260
SPSSE, Udaipur
Pointers with Arrays & Strings
Array of pointers:
The array of pointers represents a collection of
addresses. By declaring array of pointers, we
can save a substantial amount of memory
space.
An array of pointers point to an array of data items.
Each element of the pointer array points to an
item of the data array. Data items can be
accessed directly or by deferencing the
elements of pointer array.
Deepak Gour, Faculty- Department of IT 261
SPSSE, Udaipur
Pointers with Arrays & Strings
We can declare an array of pointers as follows:
int *inarray[10];
This statement declare an array of 10 pointers, each of
which points to the integer. The address of first
pointer is inarray[0] and so on. Before initialization,
they point to some unknown values.
Example:

#include <iostream.h>
#include <conio.h>
#include <string.h>
#include <ctype.h>

Deepak Gour, Faculty- Department of IT 262


SPSSE, Udaipur
Pointers with Arrays & Strings
void main()
{ int i=0;
char *ptr[10] = {“books”, “TV”, “computer”}
char str[25];
clrscr();
cout << “enter your favorite leisure:”;
cin >> str;
for (i=0;i<3;i++)
{ if (!strcmp(str,*ptr[i]))
{ cout << “your leisure is available”;
break;
}
}
if (i==3)
cout << “your leisure is not available here”;
getch();
Deepak Gour, Faculty- Department of IT 263
} SPSSE, Udaipur
Pointers with Arrays & Strings
Pointers to functions
The pointer to function is known as callback
function. We can use this function pointers
to refer to a function using function
pointers. We can allow a C++ program to
select a function dynamically at run time.
We can also pass a function as an
argument to another function. Here the
function is passed as a pointer. The
function pointer cannot be dereferenced.
Deepak Gour, Faculty- Department of IT 264
SPSSE, Udaipur
Pointers with Arrays & Strings
C++ also allows us to compare two function
pointers.
C++ provides two function pointers as
1. Function pointer point to static member
function
2. Function pointer point to non static
member function, for non static member
function, we require hidden arguments.

Deepak Gour, Faculty- Department of IT 265


SPSSE, Udaipur
Pointers with Arrays & Strings
we can define as follows:
int (*num_function(int x));
It only creates a pointer. It does not create
actual function.
Example:
#include <iostream.h>
typedef void (*funptr) (int, int)

Deepak Gour, Faculty- Department of IT 266


SPSSE, Udaipur
Pointers with Arrays & Strings
void add (int I, int j)
{cout << i “+” << j << “=” << i+j; }
void subtraction (int I, int j)
{ cout << i “-” << j << “=” << i-j; }
void main()
{funptr ptr; ptr = &add;
ptr(1,2); ptr=&subtraction;
ptr(3,2)
}

Deepak Gour, Faculty- Department of IT 267


SPSSE, Udaipur
POINTER TO OBJECT
Object pointer are useful in creating objects at run
time. We can also use an object pointer to
access the public member of an object.
Consider a class item in which we have two
member function as getdata() and
showdata().
We can refer to the member functions of items in
two ways:
1. By using the dot operator and the object.
2. By using the arrow operator and the object
pointer.
Deepak Gour, Faculty- Department of IT 268
SPSSE, Udaipur
POINTER TO OBJECT

so x.getdata(); and x.showdata()


Is same as ptr->getdata() and ptr-> showdata();
Since *ptr is an alias of x; we can also use as
(*ptr).showdata();
Note: the parenthesis are necessary because
the dot operator has higher priority then
indirection / dereference operator.

Deepak Gour, Faculty- Department of IT 269


SPSSE, Udaipur
POINTER TO OBJECT
Example:
#include <iostream.h>
class item
{int code; float price;
public:
void getdata(int a, float b)
{code = a; price = b;}
void show()
{cout << “code:” << code;
cout << “price:” << price}
};

Deepak Gour, Faculty- Department of IT 270


SPSSE, Udaipur
POINTER TO OBJECT

const int size = 2;


int main()
{item *p = new item [size];
item *d = p; int x,I; float y;
for (i=0;i<size;i++)
{cout << “input code and price” << i+1;
cin >> x >> y; p->getdata(x,y); p++;}

Deepak Gour, Faculty- Department of IT 271


SPSSE, Udaipur
POINTER TO OBJECT

for (i=0;i<size;i++)
{ cout << “item: ” << i+1;
d->show();
}
return 0;
}

Deepak Gour, Faculty- Department of IT 272


SPSSE, Udaipur
THIS POINTER

C++ Uses a unique keyword called this to


represent a object that invokes a member
function. this is the pointer that point to the
object for which this function was called.
For example, the function call A.max() will
set the pointer this to the address of the
object A. the starting address is same as
the address of the first variable in the class
structure.

Deepak Gour, Faculty- Department of IT 273


SPSSE, Udaipur
THIS POINTER

This unique pointer is automatically passed to a


member function when it is called. The pointer
this acts as an implicit argument to all the
member function.
Example:
class X { int a; -----};
The private variable a can be used directly inside a
member function, like
a = 123;
We can also use the following statement to do the
same job as:
this->a=123;
Deepak Gour, Faculty- Department of IT 274
SPSSE, Udaipur
THIS POINTER

Recall that, when a binary operator is overloaded using


a member function, we pass only one argument to
the function. The other argument is implicitly
passed using the pointer this. One important
application of the pointer this is to return the
object it points to.
For example, the statement,
return *this;//check the output
inside a member function will return the object
that invoked the function. This statement
assumes importance when we want to compare
two or more objects inside a member function
and return the invoking object as a result.

Deepak Gour, Faculty- Department of IT 275


SPSSE, Udaipur
THIS POINTER

#include <iostream.h>
#include <cstring.h>
class person
{ char name[20]; float age;
public:
person (char *s, float a)
{strcpy(name, s); age=a; }
person & person :: greater (person & x)
{ if (x.age >= age) return x
else return *this; }
void display()
{cout << “Name: ” << name << “Age: ”}
};

Deepak Gour, Faculty- Department of IT 276


SPSSE, Udaipur
THIS POINTER

void main()
{ person P1(“Kapil”, 22.25), P2(“Kartik”, 20.50),
P3(“Lakhan”, 19.50);
person P = P1.greater(P3);
cout << “Elder person is:”
P.display();
person P = P1.greater(P2);
cout << “Elder person is:”
P.display();
}
Deepak Gour, Faculty- Department of IT 277
SPSSE, Udaipur
VIRTUAL FUNCTION
When we use the same function name in both the
base and derived class, the function in base class
is declared as virtual using the keyword virtual
preceding its normal declaration. When a function
is made virtual, C++ determines which function to
use at run time based on the type of object
pointed to by the base pointer, rather than the
type of the pointer. Thus by making the base
pointer to point to different objects, we can
execute different versions of the virtual function.

Deepak Gour, Faculty- Department of IT 278


SPSSE, Udaipur
VIRTUAL FUNCTION
#include <iostram.h>
class Base
{ public:
void display() {cout << “display base”;}
virtual void show () {cout << “show base”;}
};
class Derived : public Base
{ void display() {cout << “display derived”;}
void show () {cout << “show derived”;}
};

Deepak Gour, Faculty- Department of IT 279


SPSSE, Udaipur
VIRTUAL FUNCTION
void main()
{ Base B; Derived D; Base *bptr;
cout << “bptr points to base”;
bptr=&B;
bptr->display(); bptr->show();
cout << “bptr points to derived”;
bptr=&D;
bptr->display(); bptr->show();
}
Deepak Gour, Faculty- Department of IT 280
SPSSE, Udaipur
VIRTUAL FUNCTION
When bptr is made to point to the object D, the
statement
bptr->display(); calls only the function
associated with the Base, whereas the
statement
bptr->show(); calls the Derived version
of show. This is because the function
display() has not been made virtual in the
Base class.

Deepak Gour, Faculty- Department of IT 281


SPSSE, Udaipur
PURE VIRTUAL FUNCTION
It is normal practice to declare a function virtual
inside the base class and redefine it in the
derived class. The function inside the base
class is seldom used and only serves as a
placeholder.

Such “do-nothing” function may be defined as:


virtual void display()=0;

Deepak Gour, Faculty- Department of IT 282


SPSSE, Udaipur
PURE VIRTUAL FUNCTION
Such functions are called pure virtual function.
A pure virtual function is a function
declared in a base class that has no
definition relative to the base class.
Remember that a class containing pure
virtual function cannot be used to declare
an object of its own. Such classes are
called abstract base class.

Deepak Gour, Faculty- Department of IT 283


SPSSE, Udaipur
VIRTUAL FUNCTION
Rules for Virtual Functions:
1. The virtual function must be member of some class.
2. They cannot be static members.
3. They are accessed by using object pointers.
4. A virtual function can be a friend of another class.
5. A virtual function in a base class must be defined, even
though it may not be used.
6. The prototype of the base class version of a virtual
function and all the derived class version must be
identical. If two function with the same name have
different prototype, C++ considers them as
overloaded functions, and the virtual function
mechanism is ignored.
Deepak Gour, Faculty- Department of IT 284
SPSSE, Udaipur
VIRTUAL FUNCTION
7. We cannot have virtual constructors, but we can
have virtual destructors.
8. While a base pointer can point to any type of the
derived object, the reverse is not true. That is
to say, we cannot use a pointer to a derived
class to access an object of the base type.
9. If a virtual function is defined in a base class, it
need not be necessarily redefined in the
derived class. In such cases, calls will invoke
the base function.
Deepak Gour, Faculty- Department of IT 285
SPSSE, Udaipur
CONSOLE I/O OPERATIONS
PUT() & GET() Function
Put() is used with cout and get() is used
with cin.
Syntax:
Char c; cout.put(‘x’)
Cin.get(c); value must be
character, if we pass
the numeric value its corresponding
ASCII character will be printed.
Deepak Gour, Faculty- Department of IT 286
SPSSE, Udaipur
CONSOLE I/O OPERATIONS
Example:
#include <iostream.h>
void main()
{int count = 0; char c;
cout << “input text: ”; cin.get(c);
while (c!= ‘\n’)
{ cout.put(c); count ++; cin.get(c); }
} // check the output
Deepak Gour, Faculty- Department of IT 287
SPSSE, Udaipur
CONSOLE I/O OPERATIONS
Getline() and write() function
We can read and display a line of text more
efficiently using the line oriented I/O
functions.
The getline() function reads the whole line of
text that ends with the newline character. It
can be invoked as:
cin.getline(line, size);

Deepak Gour, Faculty- Department of IT 288


SPSSE, Udaipur
CONSOLE I/O OPERATIONS
This function call invokes the function getline() which
reads character input into the variable line. The
reading is terminated as soon as either the
newline character is encountered or size
character are read. The newline character is read
but not saved. Instead, it is replaced by the null
character.
Example:
char name[20];
cin.getline(name, 20);

Deepak Gour, Faculty- Department of IT 289


SPSSE, Udaipur
CONSOLE I/O OPERATIONS
We can also read strings using the operator >>
as follows:
cin >> name;
But cin can read strings that do not contain
white / blank space.
After reading the string, cin automatically adds
the terminating null character to the
character array.

Deepak Gour, Faculty- Department of IT 290


SPSSE, Udaipur
CONSOLE I/O OPERATIONS
Example:
#include <iostream.h>
void main()
{ int size=20; char city[20];
cout << “enter city name:”; cin >> city;
cout << “city name: ” << city;
cout << “enter city name again: ”;
cin.getline(city, size);
cout << “city name now: ” << city;
cout << “enter another city name:” ;
cin.getline(city,size);
cout << “new city name” << city;
}// check the output with city names containing white spaces

Deepak Gour, Faculty- Department of IT 291


SPSSE, Udaipur
CONSOLE I/O OPERATIONS
The write() function displays an entire line and
has the following form:

cout.write(line, size);

The first argument line represents the name of


the string to be displayed and the second
argument size indicates the number of
characters to display.

Deepak Gour, Faculty- Department of IT 292


SPSSE, Udaipur
CONSOLE I/O OPERATIONS
Example:
#include <iostream.h>
#include <string.h>
void main()
{ char *string1=“C++ “; char *string2 = “Programming”;
int m = strlen(string1); int n = strlen(string2);
for (int i=1; i<n;i++)
{ cout.write(string2,i); cout << “\n”; }
for (int i=n; i>0;i--)
{ cout.write(string2,i); cout << “\n”; }
cout.write(string1,m).write(string2,n);
cout << “\n”;
cout.write(string1,10);
}//check the output
Deepak Gour, Faculty- Department of IT 293
SPSSE, Udaipur
CONSOLE I/O OPERATIONS
Formatted console I/O Operations:
Function Tasks

Width() To specify the required field size for displaying an output


value
Precision() To specify the no. of digits to be displayed after the
decimal point of a float value
Fill() To specify a character that is used to fill the unused
portion of a field
Setf() To specify format flags that can control the form of output
display (such as left / right justification)
Unsetf() To clear the flags specified

Deepak Gour, Faculty- Department of IT 294


SPSSE, Udaipur
CONSOLE I/O OPERATIONS
Exercise for students:
Program 10.4
Program 10.5
Program 10.6
Program 10.7
Program 10.8
(from Object Oriented Programming with C++,
Third Edition by E Balagurusamy)
Deepak Gour, Faculty- Department of IT 295
SPSSE, Udaipur
WORKING WITH FILES
Details of File stream classes
Class Contents

Filebuf Its purpose is to set the file buffers to read and write. Contains
Openprot constant used in the open() of file stream classes.
Also contain close() and open() as members.
Fstreambase Provides operations common to the file streams. Serves as a
base of fstream, ifstream, and ofstream class. Contains open()
and close() functions.
Ifstream Provides input operations. Inherits get(), getline(), read(), seekg()
and tellg() functions from istream.

Ofstream Provides output operations. Inherits put(), seekp(), tellp(), write()


functions from ostream.

fstream Provides supports for simultaneous input and output operations.


Inherits the functions from isstream and osstream classes
through iostream.
Deepak Gour, Faculty- Department of IT 296
SPSSE, Udaipur
WORKING WITH FILES (contd.)
Opening a file:

A file can be opened in two ways:

1. Using the constructor function of the class.


2. Using the member function open() of the
class.

Deepak Gour, Faculty- Department of IT 297


SPSSE, Udaipur
WORKING WITH FILES (contd.)
Opening file using constructor:
A constructor is used to initialize an object while it is
being created. Here, a filename is used to
initialize the file stream object.
This involves the following steps:
a) Create a file stream object to manage the stream
using the appropriate class i.e. the class ofstream
is used to create the output stream and the class
ifstream is used to create the input stream.
b) Initialize the file object with the desired filename.

Deepak Gour, Faculty- Department of IT 298


SPSSE, Udaipur
WORKING WITH FILES (contd.)
Example: This program uses a single file for
both writing and reading the data. First, it
takes data from keyboard and writes it to
the file. After the writing is completed, the
file is closed. The program again open the
same file, reads the information already
written to it and displays the same.

Deepak Gour, Faculty- Department of IT 299


SPSSE, Udaipur
WORKING WITH FILES (contd.)
#include <iostream.h>
#include <fstream.h>
void main()
{ ofstream outfile(“Item”);
cout << “Enter item name: ”;
char name[30]; cin >> name;
outfile << name << “\n” ;
cout << “Enter item cost: ”;
float cost; cin >> cost;
outfile << cost << “\n” ;

Deepak Gour, Faculty- Department of IT 300


SPSSE, Udaipur
WORKING WITH FILES (contd.)
outfile.close();
ifstream infile(“Item”);
infile >> name; infile >> cost;
cout << “\n”;
cout << “item name: ” << name;
cout << “item cost” << cost;
infile.close();
}//check the output

Deepak Gour, Faculty- Department of IT 301


SPSSE, Udaipur
WORKING WITH FILES (contd.)
Opening file using open()
Syntax:
file_stream_class stream_object;
stream_object.open(“file_name”);
Example:
ofstream outfile;
outfile.open(“data1”); outfile.close();
outfile.open(“data2”); outfile.close();
Deepak Gour, Faculty- Department of IT 302
SPSSE, Udaipur
WORKING WITH FILES (contd.)

The previous program segment opens two


files in sequence for writing the data.
Note that the first file is closed before
opening the second one. This is
necessary because a stream can be
connected to only one file at a time.

Deepak Gour, Faculty- Department of IT 303


SPSSE, Udaipur
WORKING WITH FILES (contd.)
#include <iostream.h>
#include <fstream.h>
void main()
{ofsteam fout; fout.open(“country”);
fout << “United states of America\n”;
fout << “United Kingdom\n”;
fout << “South Korea\n”;
fout.close();
Deepak Gour, Faculty- Department of IT 304
SPSSE, Udaipur
WORKING WITH FILES (contd.)
fout.open(“capital”);
fout << “Washington\n”;
fout << “London\n”;
fout << “seoul\n”;
fout.close();
const int N = 80;
char line[N];
ifstream fin;
fin.open(“country”);
Deepak Gour, Faculty- Department of IT 305
SPSSE, Udaipur
WORKING WITH FILES (contd.)
cout << “contents of country file\n”;
while(fin)
{ fin.getline(line,N); cout << line; }
fin.close();
fin.open(“capital”);
cout << “\ncontents of capital file\n”;
while(fin)
{ fin.getline(line,N); cout << line; }
fin.close();
} //check the output

Deepak Gour, Faculty- Department of IT 306


SPSSE, Udaipur
WORKING WITH FILES (contd.)
At times we may require to use two or more
files simultaneously. For example, we may
require to merge two sorted files into a
third sorted file. This means, both the
sorted flies have to kept open for reading
and the third one kept open for writing. In
such cases we need to create two
separate input stream for handling two
input files and one output stream for
handling the output file.
Deepak Gour, Faculty- Department of IT 307
SPSSE, Udaipur
WORKING WITH FILES (contd.)
#include <iostream.h>
#include <fstream.h>
#include <stdlib.h>
void main()
{ const int size = 80; char line[size];
ifstream fin1, fin2;
fin1.open(“country”); fin2.open(“capital”);
for (int i=1;i<=10;i++)
{ if (fin1.eof()!=0)
{ cout << “exit from country\n”;
exit(1);
}

fin1.getline(line,size); cout << “capital of ” << line;

Deepak Gour, Faculty- Department of IT 308


SPSSE, Udaipur
WORKING WITH FILES (contd.)
if (fin2.eof()!=0)
{ cout << “exit from capital\n”;
exit(1);
}

fin2.getline(line,size);
cout << line;
}
}
The output will be shown like:
Capital of United states of america
Washington
--------- and so on.

Deepak Gour, Faculty- Department of IT 309


SPSSE, Udaipur
WORKING WITH FILES (contd.)
Detecting eof()

While (fin)
An ifstream object, such as fin, returns a value
of 0 if any error occurs in the file operation
including the eof condition. Thus the while
loop terminates when fin returns a value of
0 on reaching the eof condition.

Deepak Gour, Faculty- Department of IT 310


SPSSE, Udaipur
WORKING WITH FILES (contd.)
There is another approach to detect the eof
condition as
if (fin1.eof()!=0) {exit(1);}
eof() is a member function of ios class. It
returns a non-zero value if the end of file
condition is encountered and a zero
otherwise. Therefore, the above statement
terminates the program on reaching the
eof.

Deepak Gour, Faculty- Department of IT 311


SPSSE, Udaipur
WORKING WITH FILES (contd.)
We have used ifstream and ofstream
constructors and the function open() to
create new files as well as to open the
existing files. In both the cases, we have
used only one argument as the filename.
However, these function can take two
arguments, the second one for specifying
the file mode.

Deepak Gour, Faculty- Department of IT 312


SPSSE, Udaipur
WORKING WITH FILES (contd.)
Syntax:
stream-object.open(“filename”,mode);
The second argument specify the purpose for
which the file is opened.

Se next slide for file mode parameters.

Deepak Gour, Faculty- Department of IT 313


SPSSE, Udaipur
WORKING WITH FILES (contd.)
FILE MODE PARAMETERS
Parameter Meaning

Ios::app Append to end of file

Ios::ate Go to end of file on opening

Ios::binary Binary file

Ios::in Open file for reading only

Ios::nocreate Open fails if the file does not exist

Ios::noreplace Open fails file the file already exist

Ios::out Open file for writing only

Ios::trunc Delete the contents of the file if it exists

Deepak Gour, Faculty- Department of IT 314


SPSSE, Udaipur
WORKING WITH FILES (contd.)
File pointers and their manipulations:
Each file has its two associated pointers known
as the file pointers. One of them is called
the input pointer (or get pointer) and the
other is called the output pointer (or put
pointer). We can use these pointers to
move through the files while reading or
writing.

Deepak Gour, Faculty- Department of IT 315


SPSSE, Udaipur
WORKING WITH FILES (contd.)
The input pointer is used for reading the
content of the given file location and the
output pointer is used for writing to a given
file location. Each time an input or output
operation takes place, the appropriate
pointer is automatically advanced.

Deepak Gour, Faculty- Department of IT 316


SPSSE, Udaipur
WORKING WITH FILES (contd.)
Functions for manipulation of file pointers:

seekg() moves get pointer to a specified


location
seekp() moves put pointer to a specified
location
tellg() give the current position of the get
pointer
tellp() gives the current position of the put
Deepak Gour, Faculty- Department of IT 317
SPSSE, Udaipur
pointer
WORKING WITH FILES (contd.)
Sequential Input and Output operations:
The file stream class support a number of
member function for performing the input
and output operations on files.
One pair of function put() and get() are
designed for handling a single character at
a time.

Deepak Gour, Faculty- Department of IT 318


SPSSE, Udaipur
WORKING WITH FILES (contd.)
Another pair of function write() and read() are
designed to write and read blocks of binary
data.

Exercise:
Program 11.4
Program 11.5
(from Object Oriented Programming with C++,
Third Edition by E Balagurusamy)
Deepak Gour, Faculty- Department of IT 319
SPSSE, Udaipur
WORKING WITH FILES (contd.)
Reading and Writing a Class Object:
One of the shortcoming of the I/O system in
C is that it cannot handle user-defined
data types such as class objects. Since
the class objects are the central
elements of C++ programming, it is
quite natural that the language
supports features for writing to and
reading from the disk file objects
directly.
Deepak Gour, Faculty- Department of IT 320
SPSSE, Udaipur
WORKING WITH FILES (contd.)
The binary input and output functions read() and
write() are designed to do exactly this job. These
functions handles the entire structure of an object
as a single unit.
One point to remember is that only data members are
written to the disk file and the members are not.
Exercise:
Program 11.6
(from Object Oriented Programming with C++, Third
Edition by E Balagurusamy)

Deepak Gour, Faculty- Department of IT 321


SPSSE, Udaipur
WORKING WITH FILES (contd.)
Updating a file: Random Access
Updating is a routine task in the maintenance of any
data file. The updating would include one or more
of the following tasks:
1. Displaying the contents of a file
2. Modifying an existing item
3. Adding a new item
4. Deleting an existing item
Exercise:
Program 11.7
(from Object Oriented Programming with C++, Third
Edition by E Balagurusamy)
Deepak Gour, Faculty- Department of IT 322
SPSSE, Udaipur
WORKING WITH FILES (contd.)
Error handling during file operations:
One of the following things may happen when dealing
with the file:
1. A file which we are attempting to open for reading
does not exist.
2. The file name used for a new file may already
exist.
3. We may attempt an invalid file.
4. There may not be any space in the disk for
saving more data.
5. We may use an invalid file name.
6. We may attempt to perform an operation when
the file is not opened for that purpose.
Deepak Gour, Faculty- Department of IT 323
SPSSE, Udaipur
WORKING WITH FILES (contd.)
ERROR HANDLING FUNCTIONS
Function Return value and meaning
Eof() Returns true (non zero) if end of file is encountered
while reading; otherwise return false (zero)
Fail() Returns true when an input or output operation has
failed
Bad() Returns true if an invalid operation is attempted or
any unrecoverable error has occurred. However, if
it is false, it may be possible to recover from any
other error reported, and continue operation.
Good() Returns true if no error occurred. This means all
the above functions are false. When it returns
false, no further operation can be carried out

Deepak Gour, Faculty- Department of IT 324


SPSSE, Udaipur
EXCEPTION HANDLING
The two most common types of bugs are logic
errors and syntactic errors.

The logic error occurred due to poor


understanding of the problem.

The syntactic errors arise due to poor


understanding of the language itself.
Deepak Gour, Faculty- Department of IT 325
SPSSE, Udaipur
EXCEPTION HANDLING (contd.)
We often come across some peculiar
problems other than the two
mentioned problems. They are known
as EXCEPTIONS.
Exceptions are runtime anomalies that a
program may encounter while
executing. It may include conditions
as division by zero, access to an
array outside of its boundary etc.
Deepak Gour, Faculty- Department of IT 326
SPSSE, Udaipur
EXCEPTION HANDLING (contd.)
Exception handling was not part of the
original C++. It is a new feature added
to ANSI C++. Today, almost all the
compilers support this features. C++
exception handling provides a
integrated approach for coping with
the unusual predictable problems
that arises while executing a
program.

Deepak Gour, Faculty- Department of IT 327


SPSSE, Udaipur
EXCEPTION HANDLING (contd.)
Basics of exception handling:
Exceptions are two kinds as synchronous and
asynchronous exceptions.
Errors such as out of range index or overflow belong to
synchronous exceptions.
The errors that are caused by events beyond the
control of the program are called asynchronous
exceptions. The proposed exception handling
mechanism in C++ is designed to handle only
synchronous exceptions.
Deepak Gour, Faculty- Department of IT 328
SPSSE, Udaipur
EXCEPTION HANDLING (contd.)
The mechanism suggests a separate error
handling code that performs the following
tasks:
1. Find the problem (HIT EXCEPTION)
2. Inform that an error has occurred (THROW
EXCEPTION)
3. Receive the error information (CATCH
EXCEPTION)
4. Take action (HANDLE EXCEPTION)
Deepak Gour, Faculty- Department of IT 329
SPSSE, Udaipur
EXCEPTION HANDLING (contd.)
C++ exception handling mechanism is basically
built upon three keywords as:

1. TRY
2. THROW
3. CATCH

Deepak Gour, Faculty- Department of IT 330


SPSSE, Udaipur
EXCEPTION HANDLING (contd.)
……..
try
{ ……..
throw exception;
……..
}
catch (type arg)
{ …….
}
Deepak Gour, Faculty- Department of IT 331
SPSSE, Udaipur
EXCEPTION HANDLING (contd.)
Example:
#include <iostream.h>
void main()
{ int a,b;
cout << “enter value of a and b”;
cin >> a; cin >> b; int x = a-b;
try
{ if (x!=0) cout << “Result is:” << a/x;
else throw(x);
}

Deepak Gour, Faculty- Department of IT 332


SPSSE, Udaipur
EXCEPTION HANDLING (contd.)
catch (int i)
{cout << “exception caught: x = ” << x; }
cout << “end”;
} // check the answer with following input
a=10, b=2
a=20, b=20

Deepak Gour, Faculty- Department of IT 333


SPSSE, Udaipur
EXCEPTION HANDLING (contd.)
More often, exceptions are thrown by functions
that are invoked from within the try blocks.
The point at which the throw is executed is
called the throw point. Once an exception
is thrown to the catch block, control cannot
return to the throw point. This kind of
relationship is as follows:

Deepak Gour, Faculty- Department of IT 334


SPSSE, Udaipur
EXCEPTION HANDLING (contd.)
type function(arg list)
{ ….
throw(object); ……. // throw exception
}
……..
try
{ …….. //invoke function here
}
catch (type arg)
{ ……… // handles exception here
}

Deepak Gour, Faculty- Department of IT 335


SPSSE, Udaipur
EXCEPTION HANDLING (contd.)
Exercise for students:
Program 13.2
Program 13.3
Program 13.4
Program 13.5
Program 13.6
(from Object Oriented Programming with C++,
Third Edition by E Balagurusamy)
Deepak Gour, Faculty- Department of IT 336
SPSSE, Udaipur

Вам также может понравиться